Programs often need to make decisions.
For example:
If the user is 18 or older, allow access.
If the password is correct, log the user in.
If the score is high enough, show "Passed".
Python uses the if statement to make these decisions.
What is an if Statement?
An if statement executes a block of code only when a given condition is True.
The basic syntax is:
if condition:
# code to executeFor example:
age = 20
if age >= 18:
print("You are an adult")Output:
You are an adultSince age >= 18 is True, Python executes the print() statement.
Indentation is Important
Notice the indentation:
if age >= 18:
print("You are an adult")The indented code belongs to the if block.
Python commonly uses 4 spaces for indentation.
This is incorrect:
if age >= 18:
print("You are an adult")It will result in an IndentationError.
Using Comparison Operators
if statements are commonly used with comparison operators.
marks = 75
if marks >= 40:
print("You passed!")Here, Python checks whether marks >= 40 is True.
You can use operators such as:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal toUsing if with User Input
We can combine if with input() to make interactive programs.
age = int(input("Enter your age: "))
if age >= 18:
print("You can vote.")If the user enters 20:
You can vote.If the user enters 15, nothing is printed because the condition is False.
Multiple Statements Inside if
An if block can contain multiple statements.
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("You can apply for a driving license")All three statements execute when the condition is True.
Using Logical Operators
You can combine multiple conditions using and, or, and not.
For example:
age = 25
if age >= 18 and age <= 60:
print("Eligible")Both conditions must be true for the message to be displayed.
Nested if Statements
You can place one if statement inside another.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")Here, the second condition is checked only if the first condition is true.
Nested if statements can be useful, but when conditions become complicated, other approaches such as elif or logical operators may make the code easier to read.
A Practical Example
Let's create a simple result checker:
marks = int(input("Enter your marks: "))
if marks >= 40:
print("Congratulations! You passed.")If the user enters:
Enter your marks: 75Output:
Congratulations! You passed.The if statement is one of the most important building blocks in Python because it allows your programs to make decisions instead of simply executing every line from top to bottom.