Conditional statements are used to perform different actions based on different conditions. In Python, the primary conditional statements are:
if
if-else
if-elif-else
if
StatementThe if
statement is used to execute a block of code only if a specified condition is True
.
if condition:
# Code to execute if the condition is True
age = 20
if age >= 18:
print("You are eligible to vote.")
if-else
StatementThe if-else
statement adds an alternative block of code to execute if the condition is False
.
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
if-elif-else
StatementThe if-elif-else
statement is used to check multiple conditions. It executes the first block of code where the condition is True
.
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if none of the conditions are True
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
Conditional statements can be nested inside one another.
number = 15
if number > 0:
if number % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Negative number")
if
and if-else
Python allows you to write conditional statements in a short-hand form when there is only one statement in the block.
if
if condition: action
age = 20
if age >= 18: print("You are eligible to vote.")
if-else
action_if_true if condition else action_if_false
age = 16
print("Eligible to vote" if age >= 18 else "Not eligible to vote")
Objective: Write Python scripts using different types of conditional statements.
Create a Python Script:
Create a file named conditional_statements.py
.
Check Even or Odd: Write a program that takes an integer input and prints whether the number is even or odd.
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
Grade Calculator: Write a program to input a student's marks and print the grade based on the following:
Age Eligibility: Write a program to check eligibility for voting, driving, and senior citizen benefits based on age.
Nested Conditions: Write a program to check if a number is positive, negative, or zero. If positive, check if it is even or odd.