0
0
Pythonprogramming~5 mins

If–else execution flow in Python

Choose your learning style9 modes available
Introduction

If-else helps your program make choices. It runs one set of instructions if something is true, and another set if it is not.

Deciding what to do based on user input, like checking if a password is correct.
Choosing different actions depending on the time of day, like saying good morning or good evening.
Checking if a number is positive or negative and acting accordingly.
Showing a message if a list is empty or has items.
Syntax
Python
if condition:
    # code to run if condition is true
else:
    # code to run if condition is false

The condition is a question your program asks, which is either true or false.

Indentation (spaces before code) shows which lines belong to if or else.

Examples
This checks if age is 18 or more. If yes, it prints a message saying you can vote. Otherwise, it says you are too young.
Python
if age >= 18:
    print("You can vote.")
else:
    print("You are too young to vote.")
This decides what message to show based on the temperature.
Python
if temperature > 30:
    print("It's hot outside.")
else:
    print("It's not too hot today.")
Sample Program

This program checks the temperature and prints a message. Since 25 is not greater than 30, it prints the else message.

Python
temperature = 25
if temperature > 30:
    print("It's hot outside.")
else:
    print("It's not too hot today.")
OutputSuccess
Important Notes

You can add more choices using elif (else if) for multiple conditions.

Always make sure your conditions cover all cases you want to handle.

Summary

If-else lets your program choose between two paths.

Use it to run code only when certain conditions are true or false.

Indentation is important to show which code belongs to each part.