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

#!/usr/bin/env python
#
# 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 ("""...""").

#!/usr/bin/env python
#
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:

#!/usr/bin/env python
#
# 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 just a first introduction to control structures. They will be covered in more detail during the next two weeks.

#!/usr/bin/env python
# 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 ...".