In the previous lesson, you learned how the if statement executes a block of code only when a condition is True. However, many real-world situations require a program to perform one action when a condition is true and a different action when the condition is false.
For example:
In all these situations, there are two possible outcomes. The program must choose one of them depending on whether the condition is true or false.
This is where the Python if...else statement becomes useful. It allows a program to execute one block of code when the condition is True and another block when the condition is False.
The if...else statement is one of the most frequently used control flow statements in Python. It helps create interactive applications, validate user input, implement business rules, and control the behavior of programs based on different conditions.
After completing this lesson, you will be able to:
if...else statement.if and if...else.if...else statement.if...else.if...else Statement?The if...else statement is a conditional statement that allows Python to choose between two different blocks of code.
If the specified condition evaluates to True, Python executes the code inside the if block. If the condition evaluates to False, Python skips the if block and executes the code inside the else block.
Unlike a simple if statement, where nothing happens when the condition is false, the if...else statement guarantees that one of the two blocks will always execute.
if condition:
statement1
else:
statement2
The syntax contains four important parts:
if keyword.True or False.else keyword.if...else Statement WorksThe execution follows these steps:
True, the if block executes.False, the else block executes.Only one block executes during each program run.
if and if...elseif Statement |
if...else Statement |
|---|---|
| Executes code only when the condition is true. | Executes one block if the condition is true and another if it is false. |
| No action occurs when the condition is false. | One of the two blocks always executes. |
| Used when only one outcome is needed. | Used when two possible outcomes exist. |
ifmarks = 75
if marks >= 40:
print("Pass")
print("Result Declared")
Output
Pass
Result Declared
if...elsemarks = 30
if marks >= 40:
print("Pass")
else:
print("Fail")
print("Result Declared")
Output
Fail
Result Declared
The else block ensures that a message is displayed even when the condition is false.
Just like the if statement, the if...else statement depends on proper indentation. Python uses indentation to determine which statements belong to the if block and which belong to the else block.
age = 17
if age >= 18:
print("Adult")
else:
print("Minor")
Output
Minor
age = 17
if age >= 18:
print("Adult")
else:
print("Minor")
Output
IndentationError: expected an indented block
Every statement inside the if and else blocks must be indented consistently.
if...else ProgramLet’s write a simple program that checks whether a person is eligible to vote.
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Output
You are eligible to vote.
Now change the value of age to 16.
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Output
You are not eligible to vote.
The program automatically selects the correct block based on the value of age.
if...else Statement?The if...else statement should be used whenever there are exactly two possible outcomes.
Common examples include:
Whenever your program needs to choose between two alternatives, the if...else statement is usually the best choice.
In this section, you learned the purpose of the Python if...else statement and how it differs from a simple if statement. You explored its syntax, execution flow, indentation rules, and created your first decision-making programs with two possible outcomes. You also learned when an if...else statement is the appropriate choice. In the next section, you will learn how to use comparison operators, Boolean values, user input, and nested if...else statements to build more interactive Python programs.
The real strength of the if...else statement comes from the conditions used to make decisions. These conditions are created using comparison operators, Boolean values, variables, mathematical expressions, and user input.
In this section, you will learn how to write effective conditions, use Boolean variables directly, work with user input, and build more powerful programs using nested if...else statements.
if...elseComparison operators compare two values and return either True or False. The result determines which block of the if...else statement will execute.
| Operator | Description | Example |
|---|---|---|
== |
Equal to | x == y |
!= |
Not equal to | x != y |
> |
Greater than | x > y |
< |
Less than | x < y |
>= |
Greater than or equal to | x >= y |
<= |
Less than or equal to | x <= y |
number = 25
if number > 20:
print("The number is greater than 20.")
else:
print("The number is 20 or smaller.")
Output
The number is greater than 20.
password = "python123"
if password == "python123":
print("Access Granted")
else:
print("Access Denied")
Output
Access Granted
Since Boolean variables already contain either True or False, they can be used directly in an if...else statement.
is_member = True
if is_member:
print("Member Discount Applied")
else:
print("Regular Price")
Output
Member Discount Applied
is_logged_in = False
if is_logged_in:
print("Welcome!")
else:
print("Please log in first.")
Output
Please log in first.
if...elseOne of the most common uses of the if...else statement is making decisions based on user input.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Sample Output
Enter your age: 16
You are not eligible to vote.
In this example:
input() returns the value as a string.int() converts it into an integer.if...else statement decides which message to display.username = input("Enter username: ")
if username == "admin":
print("Login Successful")
else:
print("Invalid Username")
Both the if block and the else block can contain multiple statements.
marks = 72
if marks >= 40:
print("Congratulations!")
print("You passed the examination.")
print("Collect your result.")
else:
print("Better luck next time.")
print("Prepare for the next examination.")
Output
Congratulations!
You passed the examination.
Collect your result.
All statements inside the selected block execute because they belong to the same indentation level.
if...else StatementsYou can place one if...else statement inside another. This is called a nested if…else statement.
Nested statements are useful when one decision depends on another.
age = 22
has_id = True
if age >= 18:
if has_id:
print("Entry Allowed")
else:
print("ID Card Required")
else:
print("Not Eligible")
Output
Entry Allowed
Python first checks whether the person is at least 18 years old. If that condition is true, it then checks whether the person has an ID card.
= Instead of ==Incorrect
x = 10
if x = 10:
print("Equal")
This causes a SyntaxError.
Correct
x = 10
if x == 10:
print("Equal")
else:
print("Not Equal")
Incorrect
age = 20
if age >= 18
print("Adult")
The colon (:) is mandatory after the condition.
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
This results in an IndentationError.
age = "20"
if age >= 18:
print("Adult")
This produces a TypeError because a string cannot be compared directly with an integer.
In this section, you learned how to use comparison operators, Boolean variables, and user input with the Python if...else statement. You explored how multiple statements can be placed inside conditional blocks, learned the concept of nested if...else statements, and reviewed common beginner mistakes such as incorrect indentation, missing colons, and confusing the assignment operator with the equality operator. In the next section, you will apply these concepts by building practical programs such as checking even and odd numbers, determining pass or fail, validating passwords, comparing numbers, and following best practices for writing clean conditional code.
Understanding the syntax of the if...else statement is only the first step. To become confident in Python programming, you need to apply it to solve real-world problems. The if...else statement is used in almost every application, from login systems and banking software to online shopping websites and mobile apps.
In this section, you will build several practical programs that demonstrate how the if...else statement is used in everyday programming. These examples will help you understand how conditional logic controls the behavior of a program.
if...else StatementA number is even if it is divisible by 2. Otherwise, it is odd.
number = 17
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Output
The number is odd.
This program checks whether a student has passed an examination.
marks = 38
if marks >= 40:
print("Congratulations! You passed.")
else:
print("Sorry! You failed.")
Output
Sorry! You failed.
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Output
You are eligible to vote.
num1 = 45
num2 = 32
if num1 > num2:
print("The larger number is:", num1)
else:
print("The larger number is:", num2)
Output
The larger number is: 45
number = -12
if number >= 0:
print("Positive Number")
else:
print("Negative Number")
Output
Negative Number
password = input("Enter Password: ")
if password == "Python123":
print("Login Successful")
else:
print("Incorrect Password")
Sample Output
Enter Password: Python123
Login Successful
if...elseMost real-world Python programs accept input from users and make decisions based on that input.
balance = 5000
amount = int(input("Enter withdrawal amount: "))
if amount <= balance:
print("Transaction Successful")
else:
print("Insufficient Balance")
Sample Output
Enter withdrawal amount: 3000
Transaction Successful
Here, the program compares the withdrawal amount with the available balance and displays the appropriate message.
if...else StatementUnderstanding how Python executes each line makes it easier to debug and write correct programs.
temperature = 28
if temperature > 30:
print("It is a hot day.")
else:
print("The weather is pleasant.")
print("Weather check completed.")
Execution Steps
temperature is assigned the value 28.temperature > 30.False.else block executes.print() statement executes.Output
The weather is pleasant.
Weather check completed.
if...elseChoose conditions that clearly express your program's logic.
age = 21
if age >= 18:
print("Eligible")
else:
print("Not Eligible")
Good variable names make your code easier to understand.
student_marks = 82
if student_marks >= 40:
print("Pass")
else:
print("Fail")
If a block becomes very large, consider moving some code into a function to improve readability.
Always use four spaces for indentation and keep it consistent throughout the program.
Instead of:
is_admin = True
if is_admin == True:
print("Access Granted")
else:
print("Access Denied")
Write:
is_admin = True
if is_admin:
print("Access Granted")
else:
print("Access Denied")
The second version is shorter, cleaner, and follows Python's recommended coding style.
= instead of == in the condition.:) after if or else.marks = 50
if marks >= 40
print("Pass")
else:
print("Fail")
The colon is missing after the condition, which results in a SyntaxError.
marks = 50
if marks >= 40:
print("Pass")
else:
print("Fail")
In this section, you applied the Python if...else statement to solve practical programming problems such as checking even and odd numbers, determining pass or fail, verifying voting eligibility, comparing numbers, validating passwords, and processing ATM withdrawals. You also learned how Python executes an if...else statement step by step, reviewed coding best practices, and identified common beginner mistakes. In the final section, you will review everything covered in this lesson through a summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python if...elif...else Statement.
In this lesson, you learned how the Python if...else statement allows a program to choose between two different actions based on the result of a condition. Unlike a simple if statement, which executes code only when a condition is true, the if...else statement ensures that one of two code blocks always executes.
You explored the syntax of the if...else statement, understood its execution flow, and learned the importance of proper indentation. You also used comparison operators, Boolean variables, and user input to create interactive decision-making programs.
Through practical examples, you learned how to solve common programming problems such as checking whether a number is even or odd, determining pass or fail, verifying voting eligibility, comparing two numbers, and validating passwords. These examples demonstrated how conditional statements control the behavior of Python programs.
if...else statement is used when there are two possible outcomes.True, the if block executes.False, the else block executes.if...else statement.if...else statements allow more complex decision-making.if...else statement?The if...else statement allows a program to execute one block of code when a condition is true and another block when the condition is false.
if and if...else?A simple if statement executes code only when the condition is true, whereas an if...else statement always executes one of two possible code blocks.
if and else blocks execute together?No. During one execution, only one block is executed.
else block mandatory?No. You can use an if statement without an else block if you only need to execute code when the condition is true.
if...else statement contain multiple statements?Yes. You can include any number of properly indented statements inside both the if and else blocks.
if...else statement inside another?Yes. This is known as a nested if...else statement.
Indentation tells Python which statements belong to each code block. Incorrect indentation causes an IndentationError.
if...else statement?Comparison operators such as ==, !=, >, <, >=, and <=.
if...else program that checks age and ID card availability before allowing entry.if...else statement?if...else statement work?if statement and an if...else statement?if and else blocks execute in the same run?if...else statement?if...else statement.Create a Python program that simulates a basic login system using the if...else statement.
Your program should:
Enter Username: admin
Enter Password: Python123
Login Successful. Welcome!
Program Finished.
Enter Username: admin
Enter Password: abc123
Invalid Username or Password.
Program Finished.
Excellent! You now understand how the Python if...else statement allows programs to choose between two possible actions based on a condition. This is one of the most important concepts in Python programming because it enables programs to respond intelligently to different situations.
In the next lesson, you will learn the Python if...elif...else Statement. Unlike if...else, which handles only two possible outcomes, if...elif...else allows you to evaluate multiple conditions and choose the appropriate block of code. This is useful for tasks such as grading systems, menu-driven programs, and category-based decision making.