Download Programming Basics

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming Basics
1) A first example "Hello World"
# This program says "hello" to the world
print "Hello World!"
Open the command prompt.
dir>edit hello.py
Type the program, save it and exit.To execute the python script type
dir>c:\python\python hello.py
Explanations
#
indicates a comment; the line is ignored
print a command; prints the string between the quotes
Exercises
1.1) Add a second print statement to the script from the example. (For example print "How
are you?".)
1.2) Make some random changes, for example, delete the "#" before "This program says ...".
In most cases you will get an error message. Fix the errors until the script executes again
successfully.
1.3) Type just python at the command line. This starts the interactive mode. You can now
type commands. To leave the interactive mode press the control key followd by D. Note: in
the interactive mode, you don't need the word print. Just typing "Hello World" will print it.
2) A second example
# A program for greeting people
name = raw_input ("What is your name? ")
print "Hello, " + name + "! How are you?"
print "My name is" , name
Explanations
name
a variable for a "name"
=
an assignment operator
raw_input input a string from the keyboard
+
concatenates strings
,
separates elements in a print statement
Exercises:
2.1) What is the difference between using "+" and "," in a print statement? Try it!
2.2) Write a program that asks two people for their names; stores the names in variables
called name1 and name2; says hello to both of them.
3) Operators for Numbers
# A program for numbers
a = 3 - 4 + 10
b=5*6
c = 7.0/8.0
print "These are the values:", a, b, c
print "Increment", a, "by one: "
a = a +1
print a
print "The sum of", a, "and", b, "is"
d=a+b
print d
number = input("Input a number ")
print number
Exercises
3.1) Execute the script. Make sure you understand every line.
3.2) Write a script that asks a user for a number. The script adds 3 to that number. Then
multiplies the result by 2, subtracts 4, subtracts twice the original number, adds 3, then prints
the result.
Operators and if statements
1) Operators for Numbers
a=b
Assign b to a
a=1+2
Add 1 and 2 and store in a
a=3-4
Subtract 4 from 3 and store in a
a=a+b
Add a and b; store in a
a=5*6
Multiply 5 and 6
a = 7.0 / 8.0 Divide 7 by 8, yields 0.875
a=7/8
Divide 7 by 8, yields 0
a = 9.0 ** 10 9 to the power of 10
a=5%2
Remainder of 5 divided by 2
int(a)
converts string into number
Exercise: Operating with Numbers
# This program converts from US $ to Canadian $
us_money = input ("Money value in US $ ")
can_money = us_money /0.6
print "US$", us_money, "= Canandian $", can_money
1.1) In analogy to the example, write a script that asks users for the temperature in F and
prints the temperature in C. (Conversion: Celsius = (F - 32) * 5/9 )
2) Strings
A string is delimited by double quotes ("..."). Certain special characters can be used, such as
"\n" (for newline) and "\t" (for a tab). To print the characters " and \, they must be preceded
by a backslash (\). A \ at end of line is used to continue a string on the next line. A multi-line
print statement should be enclosed by three double quotes ("""...""").
print "hello\n"
print "To print a newline use \\n"
print "She said: \"hello\""
print "\tThis is indented"
print "This is a very, very, very, very, very, very \
long print statment"
print """
This is a multi-line print statement
First line
Second line
"""
Exercise:
2.1) Write a python script that prints the following figure
\
| /
@ @
*
\"""/
3) Operators and functions for strings
a = b + c concatenate b and c
a = b * c b repeated c times
a[0]
the first character of a
len(a)
the number of characters in a
min(a)
the smallest element in a (alphabetically first)
max(a)
the largest element in a (alphabetically last)
Example:
# String operations
b = "the"
c = "cat"
d = " is on the mat"
a=b+""+c+d
print a
b=b+""
a=b*5
print a
print "The first character of", c, "is" ,c[0]
print "The word \""+ c+ "\" has", len(c) ,"characters"
name = raw_input ("Please, type in your name ")
name = (name + "!") * 5
print name
Exercise:
3.1) Write a program that asks users for their favourite color. Create the following output
(assuming "red" is the chosen color). Use "+" and "*".
red red red red red red red red red
red
red
red red red red red red red red red
red
red
red
red
4) Control structures: if
This is basic introduction to control structures.
# if statement
answer = raw_input("Do you like Python? ")
if answer == "yes":
print "That is great!"
else:
print "That is disappointing!"
Exercise:
4.1) Modify the program so that it answers "That is great!" if the answer was "yes", "That is
disappointing" if the answer was "no" and "That is not an answer to my question." otherwise.
Use "if ... elif ... else ...".
Logical expressions and objects
1) Logical expressions: and, or, not
For the following expressions, replace a, b, c with 1 or 0 so that the expression becomes true (i.e. 1).
Use the Python interpreter. Which expressions are logically equivalent? Record some of your results
in truth tables.
1.1)












(a and b)
(not a and b)
(not (a and b))
(a or b)
(a or not b)
(not (a or b))
(not (not a or not b))
(a and (a or b)) Does this really depend on b?
(a and b and c)
(a and b or c)
(a and (b or c))
((a and b) or c)
1.2) Write a script that asks someone to input their first name, last name and phone number.
If the user does not type at least some characters for each of these, print "Do not leave any
fields empty" otherwise print "Thank you". (Hint: if a variable is empty, its value will be
"false".)
1.3) Change the script so that the script prints "Thank you" if either the first name or the last
name or the phone number is supplied. Print "Do not leave all fields empty" otherwise.
1.4) Change the script so that only first name and last name are required. The phone number
is optional.
2) Other logical expressions for if statements
a == b
Is a equal to b?
a != b
Is a unequal to b?
a <= b
Is a smaller or equal to b?
a >= b
Is a larger or equal to b?
a<b
Is a smaller than b?
a>b
Is a larger than b?
a is b
Is a the same object as b?
a is not b Is a the not same object as b?
Note: for strings "smaller" and "larger" refers to the alphabetical order.
Exercises:
2.1) Write a program that asks a user to input a color. If the color is black or white, output "The color
was black or white". If it starts with a letter that comes after "k" in the alphabet, output "The color
starts with a letter that comes after "k" in the alphabet". (Optional: consider both capitalized and
non-capitalized words. Note: the order of the alphabet in Unix and Python is: symbols, numbers,
upper case letters, lower case letters.)
2.2) Write a program that asks a user to input a number. If the number equals "5", output "My
lucky number". If the number is larger than 10, output "What a large number!". In all other
cases, output "That's not my lucky number."
3) Objects have a name, type and value
Python code
name
value data type
greeting = "hello" greeting "hello" string
number = 1
number 1
int
Python code
name
value
answer = raw_input ("Your name: ") raw_input
data type
function
"Your name:" string
(user enters "Snoopy")
answer
choice = input ("Your age: ")
input
(user enters 104)
choice
"Snoopy"
string
function
"Your age:"
string
104
int
4) Functions for displaying types/changing types
type() displays the type of an object
str()
converts objects into printable strings
int()
converts non-integer numbers into integers
Exercise
4.1) In the Python interpreter, apply the functions type(), str(), int() to various objects (eg. "hello", 5,
raw_input). See what happens.
Optional Exercise
4.2) Ask the user to type something (use raw_input). To find out whether the input was a number,
compare whether the input is after "0" and before ":" in alphabetical order. If it is a number convert
it into an integer. Then print the input and its type. (Note: this won't work if the user enters a real
number. See below.)
5) Equality
Objects can have equal values or can be identical. A test for having equal values is ==; a test for
being the same is is. For example
>>> a = 5
>>> b = 5.0
>>> c = a
>>> a == b
1
>>> a is b
0
>>> a is c
1
Program design and control structures
1) Flowcharts: if
2) While
# while statement
answer = "no"
while answer != "yes":
answer = raw_input("Do you like Python? ")
if answer == "yes":
print "That is great!"
else:
print "That is not the right answer! Try again."
Here is an alternative version that does the same:
# while statement
#
answer = raw_input("Do you like Python? ")
while answer != "yes":
print "That is not the right answer! Try again."
answer = raw_input("Do you like Python? ")
else:
print "That is great!"
Exercises
2.1) Modify the program from above so that it asks users to "guess the lucky number". If the correct
number is guessed the program stops, otherwise it continues forever.
2.2) Modify the program so that it asks users whether they want to guess again each time.
Use two variables, number for the number and answer for the answer to the question whether
they want to continue guessing. The program stops if the user guesses the correct number or
answers "no". (In other words, the program continues as long as a user has not answered "no"
and has not guessed the correct number.)
3) Modifications of a while loop
3.1) A counter: Write a program that asks five times to guess the lucky number. Use a while loop and
a counter, such as
counter = 1
while counter <= 5:
print "Type in the", counter, "number"
counter = counter +1
The program asks for five guesses (no matter whether the correct number was guessed or
not). If the correct number is guessed, the program outputs "Good guess!", otherwise it
outputs "Try again!". After the fifth guess it stops and prints "Game over."
3.2) break: In the previous example, insert "break" after the "Good guess!" print statement.
"break" will terminate the while loop so that users do not have to continue guessing after they
found the number. If the user does not guess the number at all print "Sorry but that was not
very successful" (use "else" for this).
3.3) Counting hits: Modify the program again. This time the program continues even after
the correct number was guessed but it counts how often the correct number was guessed.
You'll need two counters: one for the while loop and another one for the number of correct
guesses. After the while loop is finished, use an if statement to print either "You guessed the
number ... times" or "The number was not guessed at all".
Note: This strategy is used in search engines: search engines display each match but keep
searching until they are through with the document collection.
4) For
Other programming languages provide "for" as an alternative for while loops with counters.
Python's "for" is more commonly used in connection with lists (see next week). But the
following code shows how Python's "for" can be used to count from 0 to a specific number.
# for statement
#
for counter in range(10):
print counter
Exercises
4.1) Modify the counter program from above using a for loop so that it asks the user for five guesses
and then stops. Use "break" to terminate the for loop as soon as the correct number is guessed.
4.2) Optional exercise: print all multiples of 13 that are smaller than 100. Use the range
function in the following manner: range(start, end, step) where "start" is the starting value of
the counter, "end" is the end value and "step" is the amount by which the counter is increased
each time.