DEV Community


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.

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!")
  print("No need for an umbrella today!") # This would be printed
Enter fullscreen mode Exit fullscreen mode

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")
    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)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.