Conditional Statements#
Programs we have seen/written so far will execute sequentially
Conditional statements execute a block of code only if specified condition(s) are met
The
if
statementExecute code only if a condition is met
The
match
statementA new addition to Python
Used for pattern matching
The if
Statement#
The
if
statementif
,elif
, andelse
are the Python keywords used in defining anif
statementThe
if
statement is a compound statement which spans multiple lines of codeTabs are used to indicate the compound statements
The
elif
andelse
blocks are optional and any number ofelif
blocks can be usedOnly the code following the first true expression of the
if
,elif
andelse
code block is executedThen the code continues to run after the entire code block
Template for an
if
conditional statement
if test_expr0:
if_body
elif test_expr1:
elif_body1
elif test_expr2:
elif_body2
\(\qquad \qquad \vdots\)
elif test_exprn:
elif_bodyn
else:
else_body
Examples of
if
statement usage
x, y = 10, 10
if x<y:
print("x is less than y")
else:
print("x is not less than y")
print('End of code')
x is not less than y
End of code
Program that prints the state of water given the temperature
# `input` function does not work with the web version; commented out
temp = 30.2 #float(input("Enter the temperature in C: "))
if temp <= 0:
print("Solid state")
elif 0 < temp <= 100: # Equivalent to 0 < temp and temp <= 100
print("Liquid state")
else:
print("Gaseous state")
Liquid state
Program to determine whether a number is even or odd
# `input` function does not work with the web version; commented out
n = 24 #int(input("Enter an Integer: "))
# No elif block
if n%2 == 0:
print(f"{n} is even")
else:
print(f"{n} is odd")
24 is even
An issue with this code is that if the user enters a non-number, we get an exception
Adding logic to ensure input is an integer
# `input` function does not work with the web version; commented out
n = "2a" #input("Enter an Integer: ")
if n.isdigit():
n = int(n)
if n%2 == 0:
print(f"{n} is even")
else:
print(f"{n} is odd")
else:
print(f"{n} is not an integer")
2a is not an integer
Program to greet a user
The
title()
andistitle()
string methods can be used to ensure correct capitalization
# `input` function does not work with the web version; commented out
name = "Butch" #input("Enter your name: ")
# check case
if not name.istitle():
name = name.title()
print(f'Hi {name}!')
Hi Butch!
Multiple elif
Blocks vs if
Blocks#
An
if
statement with multiple elif blocksThe code block following the first true
if
orelif
test expression is evaluated and the rest ignored
# An if statement with multiple elif blocks
n = 5
if n < 10:
print(f'{n} is less than 10')
elif n < 20:
print(f'{n} is less than 20')
elif n < 30:
print(f'{n} is less than 30')
print("end of code")
5 is less than 10
end of code
Modified program using multiple
if
statements to evaluate all the blocks
# Multiple standalone if statements
n = 5
if n < 10:
print(f'{n} is less than 10')
if (n >= 10) and (n < 20):
print(f'{n} is less than 20')
if (n >= 20) and (n < 30):
print(f'{n} is less than 30')
print("end of code")
5 is less than 10
end of code
The pass
Statement#
pass
is a keyword that does nothing.Useful as a placeholder in locations where Python expects code to be
n = 15
if n < 10:
print(f"{n} is less than 10")
elif n < 20:
pass
n = 5
if n < 10:
print("n is less than 10")
else:
pass
n is less than 10
The match
Statement#
The match statement is a new addition to Python 3.10
Emulates the switch-case statement in C/C++
match
andcase
are the required Python keywords
A program to respond to a choice made by the user
Alternate solution possible using the
if
statement
# `input` function does not work with the web version; commented out
query = 'Yes'.lower() #input("Do you acept the invitation? (Yes/No/Maybe): ").lower()
match query:
case 'yes':
print("Thanks for accepting!")
case 'no':
print("Sorry you cannot make it!")
case 'maybe':
print("Hope you can make it!")
case _:
print("Invalid response.")
Thanks for accepting!
Use
strip()
method to strip away leading and trailing whitespace characters (default behavior) from the inputFor non-whitespace characters, the usage is:
s.strip(chars)
wherechars
is a string made of characters that are to be stripped