Professional Documents
Culture Documents
Running IDLE
Program components
+
*
/
performs addition
performs subtraction
performs multiplication
performs division
Reading in data
Printing results
print 2, "plus", 2,
print "is", 2 + 2
Comments
Layout
average = sum / 5
print 2, "plus", 2, "is", 2 + 2
10
Compound tests
Examples
12
The if statement
if grade == "A+":
print "Congratulations!"
if score < 0 or score > 100:
print "Thats not possible!"
score = input("Enter a correct value:
")
13
if with else
if grade == "A+":
print "Congratulations!"
else:
print "You could do so much better."
print "Your mother will be
disappointed."
14
if with elif
if grade == "A":
print "Congratulations!"
elif grade == "B":
print "That's pretty good."
elif grade == "C":
print "Well, it's passing, anyway."
else:
print "You really blew it this time!"
15
Indentation
if 2 + 2 != 4:
print "Oh, no!"
print "Arithmethic doesn't work!"
print "Time to buy a new computer."
16
Example: len(courses) is 3
The len function tells you how many things are in a list
Example:
for n in range(1, 4):
print "This is the number", n
prints
This is the number 1
This is the number 2
This is the number 3
The for loop uses a variable (in this case, n) to hold the
current value in the list
18
A while loop performs the same statements over and over until
some test becomes False
Example:
n = 3
while n > 0:
print n, "is a nice number."
n = n 1
prints
3 is a nice number.
2 is a nice number.
1 is a nice number.
Calling a function
20
Defining a function
1.
2.
3.
4.
5.
6.
1.
2.
6.
def sum(numbers):
"""Finds the sum of the numbers in a list."""
total = 0
for number in numbers:
total = total + number
return total
Summary
Arithmetic: + - * / %
< <= == != >= >
Logic (boolean): True False and or not
Strings: "Double quoted" or 'Single quoted'
Lists: [1, 2, 3, 4] len(lst) range(0, 100, 5)
Input: input(question)
raw_input(question)
Decide: if test: elif test: else:
For loop: for variable in list:
While loop: while test:
Calling a function: sum(numbers)
Defining a function: def sum(numbers): return result
22
Advice to beginners
Programming is hard!
You will make many mistakes, and they will (almost) all be stupid
mistakes
The individual building blocks are all pretty simple, but they go together in
complex patterns
In a few weeks you will find that it suddenly all starts to make sense,
and you'll wonder what the problem was
Dont panic!
Theres lots of help available
23
Advice to non-beginners
24
The End
25