Loops and Conditionals: HORT 59000 Instructor: Kranthi Varala
Loops and Conditionals: HORT 59000 Instructor: Kranthi Varala
Conditionals
HORT 59000
Lecture 11
Instructor: Kranthi Varala
Relational Operators
• These operators compare the value of two
‘expressions’ and returns a Boolean value.
• String context:
• S1 += S2 add string on right to the one on left
• S1 *= A Make A copies of S1 and concatenate them to S1
Boolean Operators
Combines two or more statements that return a Boolean value.
A and B True if both A and B are true
A or B True if either A or B is true
not A reverse the Boolean given by A
xor(A,B) True if only one of A or B is True
https://upload.wikimedia.org/wikipedia/commons/4/44/LampFlowchart.png
If/elif/else statements
if test1:
statement 1
elif test2:
statement 2
else:
statement 3
• Both the elif and else blocks are optional.
If/elif/else statements
Lamp flowchart with if/else
Accepts input
from user, as
a string
Truth and Boolean tests in Python
• All objects in python have an inherent true or
false value.
• Any nonempty object is true.
• For Integers : Any non-zero number is true
• Zero, empty objects and special object ‘None’
are false.
• Comparisons return the values True or False
Loops/Iterations
• A loop is syntax structure that repeats all the
statements within the loop until the exit
condition is met.
• Statements in a loop are defined by indenting
them relative to the loop start.
• Loop ends when indentation ends.
• Python has two forms of loops: for loop and
while loop.
• E.g. >>> for x in range(10)
• E.g. >>>while (A==10)
while loops
• while condition:
statement 1
statement 2
.
.
0 1 2 3
my2DList
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
MultiDimensional Lists
my2DList = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
for x in range(len(my2DList)):
insideList=my2DList[x]
0 1 2 3
my2DList
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
MultiDimensional Lists
my2DList = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
for x in range(len(my2DList)):
for y in range(len(my2DList[x])):
print my2DList[x][y]
0 1 2 3
my2DList
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
Arbitrary dimensional Lists
subL = [[’p’,’q’],[‘r’,’s’]]
my2DList = [[1,2,3,’a’],[5,6,7,’cat’],[9,10,’e’,12],[’beta’,14,15,subL]]
0 1 2 3 Loop1
my2DList
0 1 5 9 beta
1 2 6 10 14
Loop3
Loop2 0 1
2 3 7 e 15
0 p q
3 a cat 12 1 r s
Summary: Conditions and loops