Python If Else Statement Tutorial

In Python, conditional statements are constructs that permit a program to make decisions according to specified conditions. These statements facilitate the execution of distinct blocks of code depending on whether a condition evaluates to True or False.

Types of Conditional Statements in Python

Python provides support for the following types of conditional statements:

  • if statement
  • if-else statement
  • Nested if statement
  • if-elif-else statement

Let us delve into a comprehensive examination of these conditional statements.

if Statement

Programs run the instructions contained within the if block when the condition is assessed as True.

This exemplifies the most basic form of decision-making framework. By utilizing the if statement, programs can ascertain adaptive responses as it triggers particular actions contingent upon established conditions.

Syntax:

It has the following syntax:

Example

if condition:

    # Code to execute if condition is True

Simple Python if Statement Example

Let's examine a straightforward example that illustrates how to implement an if statement in Python:

Example 1

Example

# initializing the age

age = 18

# if statement: checking if the given age is greater than or equal to 18

if age >= 18:

  # printing a message

  print("You are eligible to vote.")  # This executes because the condition is True

Output:

Output

You are eligible to vote.

Explanation:

The provided Python code utilizes an if statement to ascertain whether individuals are eligible to vote. It assesses the age criterion in comparison to 18. When the age is equal to 18, the execution of the indented block takes place, resulting in the output "You are eligible to vote." Conversely, if the age is less than 18, the condition evaluates to False, leading to the exclusion of the print statement. Indentation is a necessary aspect of Python, as it indicates which portions of the code are to be executed when the specified condition is satisfied.

Now, let us examine another instance in which the application will generate a response based on the user's provided age:

Example 2

Example

# asking age from the user

age = int(input("Enter your age: "))

# multiple if blocks

if age < 18: # checking if age is less than 18

    # printing a message

    print("You are not eligible to vote")

if age >= 18: # checking if age is greater than or equal to 18

    # printing a message

    print("You are eligible to vote.")

if age >= 21: # checking if age is greater than or equal to 21

    # printing a message

    print("You are allowed to consume alcohol in some countries.")

if age >= 60: # checking if age is greater than or equal to 60

    # printing a message

    print("You are eligible for senior citizen benefits.")

if age >= 80: # checking if age is greater than or equal to 80

    # printing a message

    print("You are a very senior citizen. Take extra care of your health.")

Output:

Output

# Output 1:

Enter your age: 20

You are eligible to vote.

# Output 2:

Enter your age: 65

You are eligible to vote.

You are allowed to consume alcohol in some countries.

You are eligible for senior citizen benefits.

Explanation:

Within a Python program, several independent if statements are utilized to assess different conditions based on the age input provided by the user. Each if statement operates independently from the others, allowing for the possibility that multiple conditions can be true at the same time.

The if statements operate independently from one another as they are kept separate. This independence allows the program to be dynamic and adaptable, as it executes all relevant code blocks when several conditions evaluate to true.

if…else Statement

At the heart of programming lies the if…else statement, which serves as a fundamental component for decision-making during code execution. When specific conditions are met and evaluated as true, one block of code is executed through the if statement; conversely, another block is executed when the conditions are assessed as false.

Various actions will be triggered based on specific conditions due to this framework. The if statement checks a condition, and if it evaluates to true, it activates the corresponding block of code; if not, the else statement is executed.

The if…else statement framework serves as an essential mechanism for handling two potential outcomes stemming from a condition, thereby improving the flexibility and adaptability of the program. In any programming language, proper indentation or the use of brackets is necessary to present code blocks in a clear and organized fashion.

Syntax:

Here is the syntax for the if...else statement.

Example

if condition:

    # Code to execute if condition is True

else:

    # Code to execute if condition is False

Python if-else Statement Example

Here's a straightforward illustration demonstrating how to implement the if...else statement in Python:

Example

Example

# asking age from the user

age = int(input("Enter your age: "))

# if-else statement: checking whether the user is eligible to vote or not

if age >= 18:

  # if block

  print("You are eligible to vote.")

else:

  # else block

  print("You are not eligible to vote.")

Output:

Output

# Output 1:

Enter your age: 20

You are eligible to vote.

# Output 2:

Enter your age: 16

You are not eligible to vote.

Explanation:

The Python application employs an if...else statement to assess the voting eligibility of individuals. Initially, the program prompts the user to input their age as an integer. The if clause checks if the provided age is greater than 18 years. If this condition holds true, the program outputs "You are eligible to vote." Conversely, if the condition is false, indicating that the age is below 18 years, the program displays "You are not eligible to vote." This approach ensures that the program delivers the appropriate response based on the user's eligibility status.

The if...else statement is essential for programs that require a choice between two possible results, as it allows for correct output determination based on user input. In Python, a coding error will arise if you fail to utilize indentation to define your code blocks properly.

Nested if…else statement

A nested if…else structure incorporates an if…else block within both the if and else segments. This arrangement enables a program to execute more sophisticated decision-making processes by facilitating the evaluation of several conditions.

The initial phase assesses the outer if statement. The inner control structure activates either the if or else segments based on newly established conditions when the outer if statement evaluates to true. This structure facilitates effective decision-making processes that incorporate multiple conditions.

In Python, proper indentation serves as the primary marker for nested blocks, in contrast to other programming languages that employ curly braces {} to delineate these structures. The nested if…else statement within another if…else construct streamlines execution in scenarios such as user authentication, grading systems, and order processing.

The implementation of conditional blocks should be approached with care, as their overuse can lead to code that is not only hard to read but also complicates the maintenance of both code clarity and efficiency.

Syntax:

Below is the structure for a nested if...else statement.

Example

if condition1:

    if condition2:

        # Code to execute if both condition1 and condition2 are True

    else:

        # Code to execute if condition1 is True but condition2 is False

else:

    # Code to execute if condition1 is False

Programs have the capability to evaluate several conditions in a systematic manner by utilizing a nested structure of if-else statements.

Initially, condition1 is assessed. The program proceeds into the first if block since condition1 is determined to be true prior to evaluating condition2. The evaluations of both the first and second conditions result in the execution of their corresponding code blocks. If condition2 is found to be false, the program will then execute the else block associated with the first if statement.

The outer else segment executes immediately when condition1 evaluates to false during the first check. This approach provides tangible advantages for making decisions that depend on several prerequisites, such as user authentication and intricate business rule execution, or various structured limitations. Proper indentation is essential in every Python program to guarantee a clear representation of the code.

Python Nested if-else Statement Example

Let us examine an illustration that demonstrates how to implement the nested if…else statement in Python.

Example 1

Example

# asking user to enter password

password = input("Enter your password: ")

# nested if-else statement: checking whether the password is strong or not

if len(password) >= 8:  # checking the length of the password

  # outer if block

  if any(char.isdigit() for char in password): # checking if the password consists of any numeral value

    # inner if block

    print("Password is strong.")

  else:

    # inner else block

    print("Password must contain at least one number.")

else:

  # outer else block

  print("Password is too short. It must be at least 8 characters long.")

Output:

Output

# Output 1:

Enter your password: secure123

Password is strong.

# Output 2:

Enter your password: password

Password must contain at least one number.

Explanation:

The application assesses the strength of a user's password utilizing a conditional if-else structure that is embedded within another if-else statement. Initially, the program prompts the user to provide a password as input. Subsequently, the program checks whether the length of the provided password meets the requirement of being at least 8 characters through the outer if statement. Within this, the inner if statement employs the any function to confirm that the password includes at least one numeric digit if the condition is met successfully. When a numeric digit is present in the input, the program outputs "Password is strong." Conversely, if the password lacks at least one number, the nested else clause triggers the message "Password must contain at least one number." If the outer else section is executed, it indicates that the entered password comprises fewer than 8 characters.

Utilizing this assessment technique, the system evaluates the criteria for both password length and password complexity to uphold appropriate security benchmarks. Consistent indentation throughout the codebase facilitates better readability in the Python programming language.

Let us examine an additional illustration that demonstrates the functionality of the nested if…else statement in Python:

Example 2

Example

# asking user to enter their marks

marks = int(input("Enter your marks: "))

# nested if-else statement: checking if the user passed with distinction or not

if marks >= 40: # checking if the user got marks greater than or equal to 40

  # outer if block

  if marks >= 75: # checking if the user got marks greater than or equal to 75

    # inner if block

    print("Congratulations! You passed with distinction.")

  else:

    # inner else block

    print("You passed the exam.")

else:

  # outer else

  print("You failed the exam. Better luck next time.")

Output:

Output

# Output 1:

Enter your marks: 80

Congratulations! You passed with distinction.

# Output 2:

Enter your marks: 35

You failed the exam. Better luck next time.

Explanation:

In the program, a nested if-else framework is implemented to determine the criteria for passing or failing based on student marks. The execution begins with the program capturing student marks as an integer input. Initially, the outer if statement checks whether the marks surpass 40, which signifies a passing grade. Following this, the inner if statement assesses if the marks exceed 75. If this condition is met, the program outputs "Congratulations! You passed with distinction." Conversely, if the marks are greater than 40 but less than or equal to 75, the code within the inner else block is executed, resulting in the message "You passed the exam." If the student marks drop below 40, the outer else clause becomes active, displaying the message "You failed the exam. Better luck next time." This organized approach effectively categorizes student academic performances for enhanced evaluation.

if…elif…else Statement

A program utilizes the if…elif…else statement to assess a series of conditions for various tests. This approach allows a program to examine multiple conditions one after another in order to identify a condition that yields a True result.

The initial phase involves evaluating the if condition, as it dictates whether the respective code block should be executed prior to assessing any subsequent elif conditions. An if statement is processed only when all preceding conditions are found to be false. If any elif condition is met, the program will execute the corresponding code, thereby bypassing any remaining conditions. The execution flow concludes at the else block when none of the conditions are fulfilled. This decision-making framework offers an effective means of handling various potential outcomes within software applications.

Syntax:

Below is the structure for an if...elif...else statement.

Example

if condition1:

    # Code to execute if condition1 is True

elif condition2:

    # Code to execute if condition2 is True

elif condition3:

    # Code to execute if condition3 is True

else:

    # Code to execute if none of the conditions are True

When a program needs to assess several conditions, it employs an if…elif…else conditional structure for evaluation.

Initially, the program evaluates condition1. Once any of the if statements satisfies the truth criterion, the corresponding code executes, after which the program exits the complete series of conditions.

The execution of condition2 occurs only after condition1 evaluates to false. The code segment associated with condition2 will run when it satisfies the truth condition.

The program advances to evaluate condition3 exclusively when both condition1 and condition2 are determined to be false. In general, the else block executes when all preceding conditions are found to be untrue.

The design mitigates the complexity associated with decision-making by allowing the execution of only one block from several if statements as soon as the initial condition evaluates to true.

Pythin if-elif-else Statement Example

Let us examine an example that demonstrates how to implement the if…elif…else statement in Python.

Example 1

Example

# asking user to enter temperature

temperature = int(input("Enter the temperature in Celsius: "))

# if-elif-else statement: checking temperature

if temperature >= 30: # if temperature is greater than or equal to 30 deg

  # if block

  print("It's a hot day.")

elif temperature >= 20: # if temperature is greater than or equal to 20 deg

  # elif block

  print("The weather is warm.")

elif temperature >= 10: # if temperature is greater than or equal to 10 deg

  # another elif block

  print("It's a cool day.")

else: # if temp is less than 10 deg

  # else block

  print("It's a cold day.")

Output:

Output

# Output 1:

Enter the temperature in Celsius: 35

It's a hot day.

# Output 2:

Enter the temperature in Celsius: 22

The weather is warm.

Explanation:

The software incorporates an efficient framework that categorizes temperature ranges, enabling a single condition to be executed based on the inputs provided. The assessment process adheres to a structured sequence designed to enhance decision-making by removing unnecessary tests. This software empowers users to access weather conditions instantly through its applications, which are tailored to specific weather scenarios. Furthermore, the program is designed to support future enhancements that could incorporate more granular temperature classifications and tailored alert notifications. The use of Python's syntax, characterized by its indentation, facilitates easier comprehension of the program's logic by maintenance teams. By utilizing its structural format, the system allows applications to automate weather alerts, provide clothing suggestions, and assist in planning based on climatic conditions. Adjustments to temperature thresholds enable this program to function effectively across a variety of climate zones, solidifying its reputation as a versatile and practical forecasting tool.

Below is an additional illustration of an if…elif…else statement that classifies exam scores according to the obtained marks.

Example

Example

# asking user to enter their marks

marks = int(input("Enter your marks: "))

# if-elif-else statement: grading marks

if marks >= 85: # if marks is greater or equal to 90, printing A

  print("Grade: A")

elif marks >= 65: # if marks is greater or equal to 80, printing B

  print("Grade: B")

elif marks >= 50: # if marks is greater or equal to 70, printing C

  print("Grade: C")

elif marks >= 33: # if marks is greater or equal to 60, printing D

  print("Grade: D")

else: # if marks is less than 90, printing F

  print("Grade: F")

Output:

Output

# Output 1:

Enter your marks: 95

Grade: A

# Output 2:

Enter your marks: 64

Grade: C

Explanation:

Utilizing its if…elif…else framework, the program processes student scores and subsequently assigns grades. Initially, it transforms the input into an integer format. The first conditional check assesses whether the scores are equal to or surpass 85 points. If this condition is met, the program outputs "Grade: A." If the scores are greater than 65 yet do not fulfill the prior if condition, it will present "Grade: B." The subsequent elif condition examines whether the student's scores fall within the range of 50 to 64, resulting in the output "Grade: C." Furthermore, the program employs another elif statement to check if the scores exceed 33, leading to the display of "Grade: D." In cases where none of the preceding conditions are satisfied, the else block executes, showcasing "Grade: F." This structure enables the program to evaluate a single condition at a time and determine the corresponding grade based on the score thresholds.

Conclusion

Decision-making is a fundamental concept in programming, as it enables programs to execute particular code based on predefined conditions. The programming language encompasses several conditional constructs, including if statements, if…else statements, nested if…else statements, and if…elif…else statements, all designed to assess conditions effectively.

Python mandates correct indentation as it plays a crucial role in ensuring code readability while also avoiding syntax errors within the program. The dynamic nature of programming, along with user interaction, is facilitated by decision-making statements that contribute to improving code efficiency. Developers who grasp these programming concepts acquire the skills necessary to create logically structured applications that effectively automate a variety of computational tasks in real-world systems.

Python if-else Statements - MCQs

  1. What is the correct syntax for an if statement in Python?
  • if z > 10 then:
  • if (z > 10)
  • if z > 10:
  • if z > 10 {}

Response: c) if z > 10:

  1. What will the result be when the subsequent code is executed?
  2. Example
    
    p = 5
    
    if p > 2:
    
        print("Hello")
    
    else:
    
        print("World")
    
  • Hello
  • World
  • No Output
  • IndentationError
  1. Which statement is used when there are multiple conditions to check?
  • ..else
  • while
  • ..elif...else

Response: d) if...elif...else

  1. What will the result of executing the subsequent code be?
  2. Example
    
    x = 14
    
    if x < 14:
    
        print("Less than 14")
    
    elif x == 14:
    
        print("Equal to 14")
    
    else:
    
        print("Greater than 14")
    
  • Less than 14
  • Equal to 14
  • Greater than 14
  • No output

Response: b) Equivalent to 14

  1. What will the result be when executing the following code?
  2. Example
    
    if 0:
    
        print("True")
    
    else:
    
        print("False")
    
  • True
  • False
  • No output

Input Required

This code uses input(). Please provide values below: