Python If Else Statement with Examples code

When you write code, you often need to check if something is true or false. For example, you might want to check if a number is greater than 5, or if a string contains a certain word. Conditional statements help you do this.

In Python, there are different types of conditional statements. The most basic one is the “if” statement. It allows you to check if a condition is true and execute a block of code based on that condition.

What are If-Else Statements in Python

If-else statements in Python are a fundamental part of programming that allows you to make decisions based on certain conditions. They help control the flow of your program and execute different blocks of code depending on whether a condition is true or false.

In Python, you can use if-else statements to create conditional logic. It’s like making choices in your program. You can set up conditions, and based on whether those conditions are true or false, your program will take different actions.

Syntax of if statement in Python

if condition:
    # code to be executed if the condition is true
else:
    # code to be executed if the condition is false

Example 1

aman_age = 25

if aman_age >= 18:
    print("You are an adult.")
else:
    print("You are not yet an adult.")

Output:

In this example, the program checks whether my age (aman age) variable is greater than or equal to 18. If it is, it will print “You are an adult.” Otherwise, it will print “You are not yet an adult.”

You are an adult.

Example 2

You can also use multiple conditions and elif (short for “else if”) statements to handle more complex scenarios. Here’s an example:

temperature = 27

if temperature > 34:
    print("It's hot Temperature")
elif temperature > 25:
    print("It's Normal Temperature.")
else:
    print("It's cool Temperature.")

Output:

In this case, the value of temperature is 27. The code evaluates the conditions sequentially:

  • The first condition temperature > 34 is not true because 27 is not greater than 34.
  • The second condition temperature > 25 is true because 27 is greater than 25. Therefore, the code executes the corresponding block and prints “Its Normal Temperature.”
It's Normal Temperature.

Flow chart of if statement 

Flowchart
Start
Condition
True
Execute Code
Next Step
False
Skip Code
End

Using If-Else with Comparison Operators

In programming, you can use if-else statements with comparison operators to make decisions based on conditions. Comparison operators are used to compare values and determine if a certain condition is true or false. Here are the common comparison operators in most programming languages:

  1. Equal to: ==
  2. Not equal to: !=
  3. Greater than: >
  4. Less than: <
  5. Greater than or equal to: >=
  6. Less than or equal to: <=

Example:

# Get user input for age
age = int(input("Please enter your age: "))

# Check the age using if-else with comparison operators
if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")

In this example, we take user input for the age, and then we use if-else with comparison operators to check the age and print different messages based on the age group.

If the age is greater than or equal to 18, it prints “You are an adult.”

If the age is between 13 and 17 (inclusive), it prints “You are a teenager.”

Otherwise, if the age is below 13, it prints “You are a child.”

Multiple Conditions with elif

When working with multiple conditions, you can use the elif statement (short for “else if”) in addition to the if and else statements.

The elif statement allows you to check for multiple conditions and execute different blocks of code based on the first condition that evaluates to True.

Example:

# Get user input for score
score = int(input("Please enter your score: "))

# Check the score using if-elif-else statements
if score >= 90:
    grade = "A"
    message = "Excellent!"
elif score >= 80:
    grade = "B"
    message = "Good job!"
elif score >= 70:
    grade = "C"
    message = "You passed."
elif score >= 35:
    grade = "D"
    message = "You need to improve."
else:
    grade = "F"
    message = "Sorry, you failed."

# Print the grade and corresponding message
print("Your grade is:", grade)
print("Message:", message)

In this example, we take user input for the score, and then we use if-elif-else statements to check the score and assign a grade and a corresponding message based on the score range. The conditions are checked in order, and the first condition that evaluates to True is executed. If none of the conditions are True, the else block is executed.

User Authentication example

User authentication is a common requirement in many applications to verify the identity of users before granting them access. Here’s a simplified example of user authentication using a username and password in Python:

# User authentication
def authenticate(username, password):
    # Define valid username and password
    valid_username = "amanmatolia"
    valid_password = "Password@12345"

    # Check if the provided username and password match the valid credentials
    if username == valid_username and password == valid_password:
        return True
    else:
        return False

# Main program
def main():
    # Get username and password from user
    username = input("Username: ")
    password = input("Password: ")

    # Authenticate user
    if authenticate(username, password):
        print("Authentication successful. Access granted.")
    else:
        print("Authentication failed. Access denied.")

# Run the main program
main()

Image Credit: Image by storyset on Freepik

Leave a Comment