DEV Community

kster
kster

Posted on

Control Flow Python ☂️🌧️

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")
Enter fullscreen mode Exit fullscreen mode

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" 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

The output would be "Wear a warm jacket today" since weather = "Cold"

Top comments (0)