Professional Documents
Culture Documents
Introduction To Python: If Statements: NCSS Workshop
Introduction To Python: If Statements: NCSS Workshop
Introduction To Python: If Statements: NCSS Workshop
NCSS Workshop
Outline
1 Control Structures
2 if statements
3 while loops
4 Practice!
,)
,WLVUDLQLQJ
7UXH )DOVH
3LFNXSXPEUHOOD 3XWRQDKDW
*RRXWVLGH
LILVBUDLQLQJ
3LFNXSXPEUHOOD
HOVH
3XWRQDKDW
*RRXWVLGH
1 >>> x = 3
2 >>> if x == 3:
3 ... print 'x is equal to 3'
4 ...
5 x is equal to 3
6 >>>
1 >>> x = 10
2 >>> if x > 3:
3 ... print 'x is bigger than 3'
4 ... if x > 6:
5 ... print 'x is also bigger than 6'
6 ...
7 x is bigger than 3
8 x is also bigger than 6
1 >>> x = 4
2 >>> if x == 3:
3 ... print 'x is equal to 3'
4 ... else:
5 ... print 'x is not equal to 3'
6 x is not equal to 3
7 >>>
1 >>> if x < 3:
2 ... print "x is less than three"
3 ... else:
4 ... if x == 3:
5 ... print "x is equal to three"
6 ... else:
7 ... print "x is greater than three"
8 ...
9 >>>
• This can get ugly once there are many alternatives
1 >>> if x < 3:
2 ... print "x is less than three"
3 ... elif x == 3:
4 ... print "x is equal to three"
5 ... else:
6 ... print "x is greater than three"
7 ...
8 >>>
• Each conditional expression is evaluated until one is True
• The corresponding block is then executed
• If none of the if or elif conditionals are True
the else block is run
and and or
• There are two additional keywords that are quite useful, and
and or.
1 >>> if name == "David" or name == "Paul":
2 ... print "That's my brother's name!"
1 >>> i = 0
2 >>> while i < 3:
3 ... print i, 'is less than 3'
4 ... i += 1
5 ...
6 0 is less than 3
7 1 is less than 3
8 2 is less than 3
9 >>>
1 >>> i = 0
2 >>> while i < 3:
3 ... print i, 'is less than 3'
4 ... i += 1
5 ...
6 0 is less than 3
7 1 is less than 3
8 2 is less than 3
9 >>>
1 >>> i = 0
2 >>> while i < 3:
3 ... print i, 'is less than 3'
4 ... i += 1
5 ...
6 0 is less than 3
7 1 is less than 3
8 2 is less than 3
9 >>>
1 >>> i = 0
2 >>> while i < 3:
3 ... print i, 'is less than 3'
4 ...
5 0 is less than 3
6 0 is less than 3
7 ...
• We’ve removed the i += 1, so the condition doesn’t change
• This is called an infinite loop
• You can interrupt an infinite loop by pressing Ctrl-C
• You should check each time to make sure they’re all there!
1 >>> i = 1
2 >>> while i < 12:
3 ... print i, 'times 5 =', i*5
4 ... i += 1
5 ...
6 1 times 5 = 5
7 2 times 5 = 10
8 ...
9 >>>