02 Intro Python
02 Intro Python
and programming
Michael Ernst
UW CSE 190p
Summer 2012
1. Python is a calculator 2. A variable is a container
Operations:
• Length:
len(myclass)
• Concatenation:
"Michael" + 'Ernst'
• Containment/searching:
'0' in myclass
"O" in myclass
3. Different types cannot be compared
Types of values
• Integers (int): -22, 0, 44
– Arithmetic is exact
– Some funny representations: 12345678901L
• Real numbers (float, for “floating point”): 2.718,
3.1415
– Arithmetic is approximate, e.g., 6.022*10**23
– Some funny representations: 6.022e+23
• Strings (str): "I love Python", ""
• Truth values (bool, for “Boolean”):
True, False
George Boole
Operations behave differently
on different types
3.0 + 4.0
3 + 4
3 + 4.0
"3" + "4"
3 + "4" # Error
3 + True # Insanity!
Type conversion:
float(15)
int(15.0)
int(15.5)
int(“15”)
str(15.5)
float(15) / 4
4. A program is a recipe
What is a program?
• A program is a sequence of instructions
• The computer executes one after the other, as if they
had been typed to the interpreter
• Saving as a program is better than re-typing from scratch
x = 1
y = 2
x + y
print x + y
print "The sum of", x, "and", y, "is", x+y
Exercise: Convert temperatures
• Make a temperature conversion chart:
Fahrenheit to Centrigrade, for -40, 0, 32, 68, 98.6, 212, 293, 451
Output:
-40 -40.0
0 -17.7778
32 0.0
68 20.0
98.6 37.0
212 100.0
293 145.0
451 232.778