Control Flow Python ☂️🌧️
kster
Posted on October 12, 2022
From our day to day we make some decisions that rely on certain situations and based on that we take further action. For example if it is raining, then bring an umbrella. In programming we find similar situations.
if statement
Using if statements we can decide whether a certain statement will be executed or not.
if is_raining:
print("Bring an umbrella")
the :
tells the computer to execute what is coming next only if the condition is met.
lets try another one
if 5 == 4 + 1:
print("True") # Output "True"
This prints out True
because the condition of the if statement is true.
if-else
What if we wanted to do something else if the condition is false? With an else statement we can run a block of code when the if statement is false.
is_raining = "No"
if is_raining == "Yes":
print("Bring an umbrella today!")
else:
print("No need for an umbrella today!") # This would be printed
elif
Using elif we can use multiple options.
weather = "Cold"
if weather == "Raining":
print("Bring an umbrella today")
elif weather =="Cold":
print("Wear a warm jacket today")
else:
print("Weather looks great today")
The output would be "Wear a warm jacket today"
since weather = "Cold"
Posted on October 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.