3 PythonControl
3 PythonControl
1
Boolean operators
and, or The tab character.
2
Boolean operators
not
3
Boolean expression
Example:
(2 > 1) and Is_even or not big
Suppose Is_even = True, and big = True.
Then the value of the boolean expression
(2 > 1) and Is_even or not big
True True True
is True
True False
True
4
The eval “command”
5
The if-else statment
Example Condition, which is an expression
with value either True or False
keywords
The if-else statment
Example
yes-statement
Evaluate
yes-statement condition
yes no
yes-stmt no-stmt
no-statement
The if-else statment
Example
12
Implement a menu
13
Implement a menu
Yes-stmt
No-stmt
14
Implement a menu
Yes-stmt
No-stmt
15
Implement a menu
Use the elif statement
…
Options of the
menu
default
In-class exercise: Magic square revisited
A magic square is a 3x3 table with nine distinct integers from 1
to 9 so that the sum of integers in each row, column, and
corner-to-corner diagonal is the same.
An example
2 7 6
9 5 1
4 3 8
17
Recall: our magic square program for
printing the row sums, column sums and
diagonal sums
19
Decision tree for sorting three integers
a>b
Y N
a>c
Y N b>c
Y
N
b>c b
N a a>c a
Y
c Y N b
c
c b
b c c a
a a a c
b b
Challenge: Write a Python program that uses only the if-else statement to
sort four integers.
20
loops/Iterations
To run a sequence of statements repeatedly using
(i) the while statement, or
(ii) the for statement
The while statement
In general
while (condition): condition
loop-body
true false
22
The while statement
Another statement for implementing loops.
i < 10?
yes no
loop
body print “Hello”
i=i +1
23
The for statement
An equivalent program using the for statement example
First, 0 assigned to i and execute loop body
Then, 1 assigned to i and execute loop body
Then, 2 assigned to i and execute loop body
...
Finally, 9 assigned to i and exectue loop body
25
What does “for i in …” really do?
loop body
27
"for i in …": … can be any group of values, even
set is allowed
28
Program for checking magic square
29
Another program for checking magic
square
30
Decision Tree Sort 3
31