Programming is not just about performing calculations or displaying information on the screen. One of the most important abilities of a computer program is its capability to make decisions. Just like humans make decisions every day based on different situations, computer programs also need to decide what action to take depending on certain conditions.
Imagine the following real-life situations:
Every one of these situations depends on a condition. If the condition is satisfied, one action is performed; otherwise, a different action may occur or no action may be taken.
Programming languages use the same concept to make decisions. In Python, the if statement is the simplest and most commonly used decision-making statement. It allows a program to execute a block of code only when a specified condition evaluates to True.
The if statement is one of the building blocks of Python programming. Almost every Python application—from simple calculator programs to websites, games, desktop applications, and artificial intelligence systems—uses if statements to control the flow of execution.
After completing this lesson, you will be able to:
if statement.if statement.if statement.if statement should be used.if Statement?The if statement is a conditional statement used to make decisions in Python. It checks whether a condition is True or False. If the condition is True, Python executes the block of code inside the if statement. If the condition is False, Python skips that block and continues with the rest of the program.
In simple words, the if statement tells Python:
“Execute this code only if the specified condition is true.”
This makes programs dynamic because their behavior can change depending on different inputs or situations.
if condition:
statement
The syntax consists of three important parts:
if.True or False.:) followed by an indented block of code.Python evaluates the condition first. Only when the condition is True does it execute the indented statements.
age = 20
if age >= 18:
print("You are eligible to vote.")
Output
You are eligible to vote.
Since the value of age is 20, the condition age >= 18 evaluates to True, so Python executes the print() statement.
age = 15
if age >= 18:
print("You are eligible to vote.")
print("Program Finished.")
Output
Program Finished.
Because the condition evaluates to False, Python skips the code inside the if block and continues executing the remaining statements.
if Statement WorksUnderstanding the execution flow of an if statement helps you write better programs.
The execution follows these steps:
if statement.True, the indented block executes.False, the block is skipped.if block.This process happens every time Python encounters an if statement.
marks = 82
if marks >= 40:
print("Congratulations!")
print("You passed the examination.")
print("Result Declared.")
Output
Congratulations!
You passed the examination.
Result Declared.
Since the condition is true, both indented statements execute before Python moves to the final print() statement.
One feature that makes Python different from many other programming languages is its use of indentation instead of braces.
Languages such as C, C++, Java, and JavaScript use curly braces ({ }) to define blocks of code. Python uses indentation (spaces or tabs) to identify which statements belong to the same block.
number = 25
if number > 10:
print("Greater than 10")
print("Condition satisfied")
print("End of program")
Output
Greater than 10
Condition satisfied
End of program
Both print() statements are indented, so both belong to the if block.
number = 25
if number > 10:
print("Greater than 10")
Output
IndentationError: expected an indented block
This error occurs because Python expects every statement inside the if block to be indented.
if block.Most modern code editors such as VS Code automatically insert the correct indentation when you press the Enter key after typing a colon (:).
if Statement?The if statement is used whenever your program must make a decision before performing an action.
Common examples include:
marks = 75
if marks >= 40:
print("Pass")
Output
Pass
stock = 10
if stock > 0:
print("Product Available")
Output
Product Available
In both examples, the code executes only when the specified condition evaluates to True.
In this section, you learned the purpose of the Python if statement and why it is one of the most important control flow statements in programming. You explored its syntax, understood how Python evaluates conditions, learned the importance of indentation, and created several simple decision-making programs. You also discovered common situations where the if statement is used in real-world applications. In the next section, you will learn how comparison operators and Boolean expressions work inside an if statement, explore multiple examples, and understand how nested if statements allow you to create more advanced decision-making logic.
The power of the if statement comes from the conditions that it evaluates. A condition is an expression that produces either True or False. Python checks this result before deciding whether to execute the code inside the if block.
Most conditions are created using comparison operators, Boolean values, variables, or expressions. Learning how to write good conditions is essential because every decision-making program depends on them.
if StatementA condition is any expression that evaluates to either True or False.
age = 20
if age >= 18:
print("Eligible to vote")
Output
Eligible to vote
Python evaluates the expression age >= 18. Since the result is True, the print() statement executes.
temperature = 35
if temperature > 30:
print("It is a hot day.")
Output
It is a hot day.
temperature = 20
if temperature > 30:
print("It is a hot day.")
print("Weather checked.")
Output
Weather checked.
The condition evaluates to False, so Python skips the if block.
if StatementComparison operators compare two values and always return either True or False.
| Operator | Meaning | 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 |
==password = "python123"
if password == "python123":
print("Access Granted")
Output
Access Granted
!=username = "Rahul"
if username != "Admin":
print("Regular User")
Output
Regular User
<=speed = 60
if speed <= 80:
print("Within Speed Limit")
Output
Within Speed Limit
You do not always need to write comparison operators. Since Boolean variables already store True or False, they can be used directly inside an if statement.
is_logged_in = True
if is_logged_in:
print("Welcome!")
Output
Welcome!
If the variable contains False, the code inside the if block will not execute.
is_logged_in = False
if is_logged_in:
print("Welcome!")
print("Please login.")
Output
Please login.
if BlockAn if block can contain one statement or multiple statements.
marks = 90
if marks >= 40:
print("Congratulations!")
print("You passed.")
print("Collect your certificate.")
Output
Congratulations!
You passed.
Collect your certificate.
All indented statements execute because the condition is True.
if StatementA nested if statement is an if statement placed inside another if statement.
Nested if statements are useful when one condition depends on another.
age = 22
has_id = True
if age >= 18:
if has_id:
print("Entry Allowed")
Output
Entry Allowed
Python first checks the outer condition. Only if it is True does it evaluate the inner if statement.
= Instead of ==One of the most common mistakes is confusing the assignment operator with the equality operator.
Incorrect
x = 10
if x = 10:
print("Equal")
This produces a syntax error.
Correct
x = 10
if x == 10:
print("Equal")
Output
Equal
age = 18
if age >= 18:
print("Adult")
This causes an IndentationError.
age = "20"
if age > 18:
print("Adult")
This results in a TypeError because a string cannot be directly compared with an integer.
In this section, you learned how conditions are created using comparison operators, Boolean variables, and expressions. You explored each comparison operator with examples, learned how multiple statements work inside an if block, and understood how nested if statements evaluate conditions step by step. You also examined common beginner mistakes, including incorrect indentation, using = instead of ==, and comparing incompatible data types. In the next section, you will build practical programs using the if statement, apply it to everyday programming problems, and learn best practices for writing clear and efficient conditional logic.
Now that you understand the syntax of the if statement and how conditions work, it is time to apply this knowledge by solving practical programming problems. Writing real programs is the best way to understand how decision-making works in Python.
The examples in this section start with simple programs and gradually become more practical. As you study them, pay attention to how the condition controls the flow of the program.
if StatementThis program checks whether a number is greater than zero.
number = 15
if number > 0:
print("The number is positive.")
Output
The number is positive.
If the value of number is positive, the message is displayed. Otherwise, the program simply skips the if block.
The modulus operator (%) returns the remainder after division. An even number always has a remainder of zero when divided by 2.
number = 18
if number % 2 == 0:
print("The number is even.")
Output
The number is even.
age = 21
if age >= 18:
print("Eligible to vote")
Output
Eligible to vote
This example demonstrates one of the most common uses of the if statement—checking eligibility based on a condition.
password = "python123"
if len(password) >= 8:
print("Password length is valid.")
Output
Password length is valid.
The len() function returns the number of characters in the password. The if statement checks whether it meets the required length.
marks = 76
if marks >= 40:
print("Pass")
Output
Pass
if StatementThe if statement becomes more useful when combined with user input.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
Sample Output
Enter your age: 20
You are eligible to vote.
In this example:
input() returns a string.int() converts it into an integer.if statement evaluates the condition.if StatementUnderstanding how Python executes each line helps you debug programs more easily.
balance = 5000
if balance >= 1000:
print("Withdrawal Allowed")
print("Transaction Completed")
Execution Steps
balance is assigned the value 5000.balance >= 1000.True.print() statement executes.Output
Withdrawal Allowed
Transaction Completed
if StatementFollowing good programming practices makes your code easier to understand and maintain.
Good Example
student_marks = 85
if student_marks >= 40:
print("Pass")
Avoid
x = 85
if x >= 40:
print("Pass")
Simple conditions are easier to read and debug.
temperature = 30
if temperature > 25:
print("Warm Weather")
Always indent code inside the if block using four spaces.
Instead of:
is_logged_in = True
if is_logged_in == True:
print("Welcome")
Write:
is_logged_in = True
if is_logged_in:
print("Welcome")
The second version is shorter and follows Python's recommended style.
Readable code is easier to maintain and understand.
salary = 45000
if salary > 30000:
print("Eligible")
:) after the if condition.= instead of ==.marks = 50
if marks >= 40
print("Pass")
This produces a SyntaxError because the colon is missing.
Correct Version
marks = 50
if marks >= 40:
print("Pass")
In this section, you applied the Python if statement to solve practical programming problems. You learned how to check positive numbers, determine whether a number is even, verify age eligibility, validate password length, and combine the if statement with user input. You also explored how Python executes an if statement step by step, reviewed coding best practices, and identified common beginner mistakes. In the final section, you will review the lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python if...else Statement.
In this lesson, you learned how the Python if statement enables programs to make decisions based on conditions. You explored its syntax, execution flow, indentation rules, and the role of Boolean expressions in determining whether a block of code should execute.
You also learned how to use comparison operators, Boolean variables, and user input with the if statement. Through practical examples, you saw how conditional logic can solve common programming problems such as checking positive numbers, validating user input, determining eligibility, and verifying passwords.
Finally, you reviewed coding best practices and common beginner mistakes to help you write clean, readable, and error-free conditional statements.
if statement is used to make decisions in Python.if block executes only when the condition evaluates to True.if statement.if block.if statements allow more complex decision-making.if statement?The if statement allows a program to execute a block of code only when a specified condition is True.
False?Python skips the code inside the if block and continues with the next statement.
Indentation defines the code block that belongs to the if statement. Incorrect indentation results in an IndentationError.
if statement?Comparison operators such as ==, !=, >, <, >=, and <=.
if statement contain multiple statements?Yes. Any number of properly indented statements can be placed inside an if block.
if statement?A nested if statement is an if statement placed inside another if statement.
if statement?Yes. A Boolean variable already contains either True or False, so it can be used directly as the condition.
= and ==?The = operator assigns a value to a variable, while == compares two values for equality.
if statement that checks both age and possession of an ID card.if statement?if statement work?if condition return?= and ==?if statement contain another if statement?if condition evaluates to False?if statement.Create a Python program that determines whether a student has passed an examination.
Your program should:
if statement to check whether the marks are 40 or above.if statement regardless of the result.Enter your name: Rahul
Enter your marks: 78
Welcome Rahul
Congratulations! You have passed.
Program Completed.
Enter your name: Amit
Enter your marks: 25
Welcome Amit
Program Completed.
Congratulations! You have learned how to use the Python if statement to make decisions based on conditions. You now understand how Python evaluates Boolean expressions, executes conditional code blocks, and uses indentation to define program structure.
In the next lesson, you will learn the Python if...else Statement. You will discover how to execute one block of code when a condition is true and another block when the condition is false, allowing you to build more complete decision-making programs.