Programming in Python
BEES 2021
Agenda
- Review: Reading User Input
- Conditional Control Flow
- If Statement
- Else
- Elif
- Pass
- Looping Control Flow
- While Loop
- Inputs are always String
- Example:
- We can use type conversion to read different types
- Example:
name = input("What's your name? ")
print(type(name))
print("Hello " + name)
print("Hello ", name, 5)
value1 = float(input("Enter a number: ")) # Read a first number from the user
value2 = float(input("Enter another number: ")) # Read a second number from the user
print("The sum of your two numbers is: " + str(value1 + value2))
USER input
-
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
pass
- Sometimes when you're writing code, you want a placeholder statement - use pass
x = 4
if x > 5:
pass # Pass acts as a placeholder for the code you will write
print(x)
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 - Lecture 3
By Narges Norouzi
BEES - Lecture 3
- 427