Conditional statements allow a program to execute different blocks of code based on specific conditions. Python provides the following conditional statements:
ifif-elseif-elif-elseif statementsif StatementThe if statement executes a block of code only if the condition evaluates to True.
if condition:
# Code to execute if condition is Trueage = 18
if age >= 18:
print("You are eligible to vote!")You are eligible to vote!
If the condition is False, the code inside if is skipped.
if-else StatementThe else block executes when the if condition is False.
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is Falsenum = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")Even numberif-elif-else StatementUse elif (short for "else if") to check multiple conditions.
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if all conditions are Falsemarks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: F")Grade: Bif StatementsYou can place one if statement inside another.
num = 15
if num > 10:
print("Greater than 10")
if num % 5 == 0:
print("Divisible by 5")Greater than 10
Divisible by 5if Statement in One Line)You can write simple if statements in a single line.
x = 5
if x > 0: print("Positive number")For if-else, use the ternary operator:
num = 7
result = "Even" if num % 2 == 0 else "Odd"
print(result)OddYou can combine multiple conditions using:
and (both conditions must be True)or (at least one condition must be True)not (negates the condition)age = 20
has_id = True
if age >= 18 and has_id:
print("Allowed to enter")Allowed to enterusername = "admin"
password = "1234"
user_input = input("Enter username: ")
pass_input = input("Enter password: ")
if user_input == username and pass_input == password:
print("Login successful!")
else:
print("Invalid credentials")if executes a block if the condition is True.if-else provides an alternative block if the condition is False.if-elif-else checks multiple conditions.if allows conditions inside another if.and, or, not) combine conditions.Sign in to join the discussion and post comments.
Sign inObject-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.
Python for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.