In Python, if else statements are used to make decisions in a program. They allow the program to execute different blocks of code depending on whether a condition is True or False.
The if statement executes a block of code only when its condition is True.
age = 20
if age >= 18:
print("You are an adult.")
if condition:
statement
The important parts are:
number = 10
if number > 5:
print("Number is greater than 5")
If the condition is False, the code inside the if block is not executed.
number = 3
if number > 5:
print("Number is greater than 5")
There is no output because the condition is False.
The else statement is used when you want to execute another block of code if the if condition is False.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
if condition:
statement
else:
statement
If the condition is True, the if block executes. Otherwise, the else block executes.
The modulus operator % can be combined with if else to check whether a number is even or odd.
number = 10
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
number = -5
if number >= 0:
print("Positive number")
else:
print("Negative number")
a = 20
b = 10
if a > b:
print("A is greater")
else:
print("B is greater or equal")
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible.")
else:
print("You are not eligible.")
If the user enters 20:
password = input("Enter password: ")
if password == "12345":
print("Login successful")
else:
print("Invalid password")
If the user enters 12345:
Strings can also be compared using conditions.
name = input("Enter your name: ")
if name == "Rahul":
print("Welcome Rahul")
else:
print("Welcome")
The and operator can be used when both conditions must be True.
age = 25
if age >= 18 and age <= 60:
print("Working age")
else:
print("Outside working age")
The or operator is used when at least one condition should be True.
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
else:
print("Weekday")
The not operator reverses a Boolean condition.
logged_in = False
if not logged_in:
print("Please login first")
An if statement can be placed inside another if statement. This is called a nested if.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Entry not allowed")
Indentation is very important in Python. The statements inside an if or else block must be indented.
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
marks = 65
if marks >= 40:
print("Pass")
else:
print("Fail")
This is a simple example of decision-making using marks.
temperature = 35
if temperature > 30:
print("It is hot")
else:
print("It is cool")
marks = int(input("Enter your marks: "))
if marks >= 40:
print("Congratulations!")
print("You passed the exam.")
else:
print("You failed the exam.")
print("Please try again.")
If the user enters 75:
Question: Which keyword is used when the if condition is False?