Programming in Python
BEES 2023
Agenda
- Conditional Control Flow
-
- If Statement
- Else
- Elif
- Looping Control Flow
- While Loop
-
Just like reading a book, recall Python reads each line of code in turn, progressively updating it's "state" (aka memory) with variables and definitions.
-
Like a choose-your-own-adventure book, the program can skip lines and jump around the book using "conditionals".
-
Imagine Python has a cursor and these conditionals cause it to skip or include lines depending on their logical value
CONDITIONAL CONTROL FLOW
if ... else ...
if boolean expresion:
stmt
else:
stmt
if "dogs" > "cats": # Strings are compared lexicographically (dictionary ordering)
print("Dogs really are the best")
else:
print("But Narges is a cat lover")
If example
Else and ElIf example
Nested conditionals
# Consider the following if/elif/else block
x = float(input("Give me a number? : "))
if not x > 2:
print("x is less than or equal to 2")
elif x < 5:
print("x is greater than 2 but less than 5")
elif x <= 10:
print("x is greater than or equal to 5 but less than or equal to 10")
else:
print("x is greater than 10")
# You can achieve the same with nested if statements:
x = float(input("Give me a number? : "))
if x < 5:
if not x > 2: # This if is nested in the outer if statement,
# it is only tested if the outer conditional evaluates to True
print("x is less than or equal to 2")
else:
print("x is greater than 2 but less than 5")
else:
if x <= 10:
print("x is greater than or equal to 5 but less than or equal to 10")
else:
print("x is greater than 10")
Inline conditionals
- We can write inline if/else statement
- Sometimes it makes the code more readable
while ...
while boolean expression:
stmt
i = 0
while i < 10:
print(" i is:", i)
i = i + 1
print("we're done!")
# You read this program as:
# Set i to 0
# check if i < 0, if it is:
# print "i is: ", i
# add one to i
# go back to the start of the while loop
# print "we're done"
While example
putting it all together
Lecture 3 challenge
Questions?
BEES 2023 - Lecture 3
By Narges Norouzi
BEES 2023 - Lecture 3
- 324