Conditional Statement
When certain condition met, do something.
Syntax
- if
- if else
- if elif
- if elif else
examples
python
price = 1000
if price > 1000:
# block of code executed when condition is truthy
print('price is more than 1000')
if price > 1000:
# block of code executed when condition is truthy
print('price is more than 1000')
else:
# block of code executed when condition is falsy
print('price is less than 1000')Falsy values
FalseNone0,0.0,0j(int, float, complex)''(empty string)[](empty list){}(empty dictionary)set()(empty set)()(empty tuple)range(0)(empty range)
Truthy values
everything else is truthy
Multiple conditions
you can use elif to add more conditions as many as you need. The order of the conditions matters when they are overlaping. If no overlaping, order of conditions does not matter.
Non-overlaping conditions
python
number = -20
if number > 0:
print('positive')
elif number < 0:
print('negative')
else:
print('zero')Overlaping conditions
Put more specific conditions first then generic conditions.
python
number = 11
if number % 3 == 0 and number % 5 == 0:
print('Number is divisible by 3 and 5')
elif number % 3 == 0:
print('Number is divisible by 3')
elif number % 5 == 0:
print('Number is divisible by 5')
else:
print('Number is not divisible by 3 and 5')Conditions inside function
function to calculate member discount
python
def calc_discount(price: int, is_member: bool):
if is_member:
# if is_member is true, discount is 10%
return price - price * 0.1
# otherwise, discount is 5%
return price - price * 0.05
# call function with keyword arguments and assign to variable
discounted_price = calc_discount(price=1000, is_member=True)
print(discounted_price)
# 900.0function to calculate German Academic Grade
python
def get_grade(score: int):
# 91 - 100
if score >= 91:
return 'Sehr Gut'
# 81 - 90
if score >= 81:
return 'Gut'
# 66 - 80
if score >= 66:
return 'befriedigend'
# 50 - 65
if score >= 50:
return 'ausreichend'
# 0 - 49
return 'nicht bestanden'
print(get_grade(85))
# 'Gut'