Programming & Numerical Analysis: Kai-Feng Chen
Programming & Numerical Analysis: Kai-Feng Chen
PROGRAMMING &
NUMERICAL ANALYSIS2014
Lecture 02: Control flow
CONTROL FLOW
CONDITIONAL
EXECUTION
One definitely needs the ability to check some certain conditions
and change the behavior of the program accordingly.
THE STRUCTURE
The condition,
which must be a
boolean expression.
if x > 0 :
print 'x is positive!'
HEADER
BODY
The body can
contain any number
of statements.
BOOLEAN EXPRESSIONS
A boolean expression is either true or false.
For example, the basic operator == compares two operands and
produces True if they are equal:
>>> 5==5
True
>>> 5==6
False
The True and False (T,F must be capital) belong to bool type:
>>> type(True)
<type 'bool'>
RELATIONAL OPERATORS
The == operator is one of the relational operators; the others are:
x
x
x
x
x
!= y
> y
< y
>= y
<= y
#
#
#
#
#
x
x
x
x
x
is
is
is
is
is
not equal to
greater than
less than y
greater than
less than or
y
y
or equal to y
equal to y
LOGICAL OPERATORS
There are three logical operators: and, or, not.
The operands of the logical operators should be boolean
ALTERNATIVE
EXECUTION
Alternative execution with two possibilities and the condition
determines which one gets executed.
The syntax:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
CHAINED
CONDITIONALS
Sometimes there are more than two possibilities one way to
express a computation like that is a chained conditional:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
NESTED
CONDITIONALS
One conditional can also be nested within another. For example:
If-else block #1
if x == y:
print 'x and y are equal'
else:
If-else block #2
if x < y:
print 'x is less than y'
else:
print 'x is greater than y'
indentation of the
statements define
the blocks.
NESTED
CONDITIONALS (II)
Indentation makes the structure apparent. But nested conditionals
become difficult to read very quickly. Good to avoid them.
if 0 < x:
if x < 10:
print 'x is a positive single-digit number.'
Simplified with and:
if 0 < x and x < 10:
print 'x is a positive single-digit number.'
11
COMMENT: INDENTATION
Leading whitespace at the beginning of lines is used to define the
indentation level of the line, which is used to determine the
grouping of statements.
INTERMISSION
Try the following logic operations:
>>> a = 1.0/3.0
>>> b = 1.0 - 2.0/3.0
>>> a == b
Do you see True or False? Why?
>>> not (((True and (True or False) and True) and
False) or False) and False or True
Do you see True or False? Why?
13
INTERMISSION (II)
Try this kind of weird-indented programs?
print "a"
print "aa"
print "aaa"
print "aaaa"
or
x = 3
if x < 4:
print "x is smaller than 4."
if x > 1:
print "x is greater than 1."
14
INTERMISSION (III)
Try this kind of weird-indented programs?
x = y = 2
if x > 1:
if y < 4:
x += y
x += y is the same as x = x + y
y += 4 is the same as y = y + 4
y += 4
elif x + y > 1:
y = (x + y)*2
else:
x -= (y / 2)
elif y == x % 2:
y = x**2
else:
x -= y**2
print x,y
15
What do you
expect to see in the
end (x,y)?
ITERATION
Computers are often used to automate repetitive tasks: repeating
identical or similar tasks.
The condition
n = 1
while n <= 10 :
print n
n += 1
TERMINATION OF THE
LOOP
The loop should change some of the variables so that eventually
the condition becomes false and ends the loop (e.g. the n+=1
statement).
18
n = 0
while True:
n += 1
if n > 10:
break
if n % 2 == 0:
continue
print n
print 'the end!'
19
LOOP ELSE
STATEMENT
Similar to the if statement, else can be attached to the end of loop.
The code block after else will be executed if the loop ended
normally (without calling the break statement):
n = 0
m = 5 if m is not between 110, the ended normally! will be printed.
while n<10:
n += 1
print n
if n==m:
print 'n ==',m,'hit. Break the loop.'
break
else:
print 'ended normally!'
20
THE PASS
STATEMENT
The pass statement does nothing. It can be used when a statement
is required syntactically but the program requires no action.
For example:
while True:
pass # this is a do-nothing, infinite loop
n = 3
if
n == 1:
print 'One!'
elif n == 2:
print 'Two!'
elif n == 3:
print 'Three!'
else:
pass do nothing, simply a placeholder for now
21
letters = 'bhJlmprsty'
for initial in letters: loop over the letters
print initial + 'ack',
Output:
back hack Jack lack mack pack rack sack tack yack
22
ACCESSING A LIST
The for statement can access to the elements in a list.
For example:
animals = ['cat','dog','horse','rabbit','mouse']
for a in animals:
print a
odd_numbers = [1,3,5,7,9]
for n in odd_numbers:
print n
The list odd_number can be actually replaced by
a simple call to the built-in function range()
23
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
The given end point (e.g. 10) is never part of the generated list.
24
RANGE() + FOR
Get a list of odd numbers:
for n in range(1,10,2):
print n
animals = ['cat','dog','horse','rabbit','mouse']
for i in range(len(animals)):
print i,'=>',animals[i]
The function len() return the number of elements in
a list or how many characters in a string.
25
>>> a = ['spam','eggs',100,1234]
>>> a
['spam', 'eggs', 100, 1234]
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2] Access to the elements in a reversed order
100
>>> a[1:2] Get a sub list
['eggs', 100]
26
INTERMISSION
Please try to find out:
Is 1237 a prime number?
30
HANDS-ON SESSION
Up to now we have gone through:
The basic structure and syntax of python
Variables and operators
Branching, conditionals, and iterations
You should be able to write a meaningful program and carry out
some interesting calculations already!
31
HANDS-ON SESSION
Practice 1:
Write a small program and print these two figures on your screen:
*
**
***
****
*****
******
*******
********
*********
**********
*
-***
---*****
-----*******
-------*********
----------
32
HANDS-ON SESSION
Practice 2:
=
=
=
=
=
=
2
4
6
8
10
12
= 81
33
HANDS-ON SESSION
Practice 3:
Find out all of the prime numbers which are smaller than 10000.
2 3 5 7 11 13 17 19 23 29 31 37 41
43 47 53 59 61 67 71 73 79 83 89
97 ... 9973
34
HOMEWORK #2
Exercise 1:
Exercise 2:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
...
ZABCDEFGHIJKLMNOPQRSTUVWXY
35