Conditional Statements
✕1. 🚦 Conditional Statements
- Imagine a traffic light.
If the light is green, vehicles move.
If the light is red, vehicles stop.
If the light is yellow, vehicles slow down.
A Python conditional statement works in a similar way. It allows a program to make decisions based on conditions.
Conditional statements are used to control the flow of code execution. They help us run different blocks of code depending on whether a condition is True or False.
Example:
age = 18if age >= 18:print("You can vote.")Output: You can vote. - A condition is an expression that gives either True or False.
Examples:
print(10 > 5)# ➜ Trueprint(10 < 5)# ➜ Falseprint(18 >= 18)# ➜ Trueprint("pdf" == "pdf")# ➜ True 📌ifstatements use these True or False results to decide which code block to run. - Indentation means the space at the beginning of a line. In Python, indentation defines the code block. Usually, we use 4 spaces for indentation.
📌 Avoid mixing spaces and tabs in the same program.
Example:
age = 18if age >= 18:print("You are an adult.")Here, the print statement belongs to theifblock because it is indented. ⚠️ If indentation is wrong, Python gives an IndentationError. 📌 Code insideif,elif, andelsemust be properly indented.
1.1 What are Conditional Statements?
1.2 Boolean Conditions
1.3 Indentation
2. ✅ if Statement
ifis used when we want to run a block of code only when a condition is True. Syntax:if condition:code to run if condition is TrueExample:age = 20if age >= 18:print("You are eligible for voting.")Output: You are eligible for voting.num = 10if num > 0:print("Number is positive.")Output: Number is positive.file_name = "report.pdf"if file_name.endswith(".pdf"):print("This is a PDF file.")Output: This is a PDF file.
2.1 What is if?
2.2 if Example with Number
2.3 if Example with String
3. 🔀 if else Statement
if elseis used when we want to run one block if the condition is True and another block if the condition is False. Syntax:if condition:code to run if condition is Trueelse:code to run if condition is FalseExample:age = 16if age >= 18:print("You are an adult.")else:print("You are a minor.")Output: You are a minor.age = 18if age >= 18:print("You are eligible for voting.")else:print("You are not eligible for voting.")Output: You are eligible for voting.num_1 = 15num_2 = 3if num_1 % num_2 == 0:print("15 is divisible by 3")else:print("15 is not divisible by 3")Output: 15 is divisible by 3
3.1 What is if else?
3.2 Voting Example
3.3 Divisibility Example
4. 🪜 if elif else Ladder
if elif elseis used when we need to check multiple conditions one by one. Python checks conditions from top to bottom. When one condition becomes True, its block runs and the remaining conditions are skipped. Syntax:if condition_1:code to run if condition_1 is Trueelif condition_2:code to run if condition_2 is Trueelif condition_3:code to run if condition_3 is Trueelse:code to run if none of the above conditions are True📌elifmeans else if. 📌 We can use multipleelifblocks. 📌elseis optional.marks = 85if marks >= 90:print("Grade: A")elif marks >= 80:print("Grade: B")elif marks >= 70:print("Grade: C")elif marks >= 60:print("Grade: D")else:print("Grade: F")Output: Grade: B 📌 Since marks is 85, the conditionmarks >= 80becomes True.file_name = "report.pdf"if file_name.endswith(".pdf"):print("This is a PDF file.")elif file_name.endswith(".docx"):print("This is a Word document.")elif file_name.endswith(".csv"):print("This is a CSV file.")else:print("Unknown file type.")Output: This is a PDF file.age = 16if age <= 12:print("You are a child.")elif age <= 19:print("You are a teenager.")elif age <= 59:print("You are an adult.")else:print("You are a senior.")Output: You are a teenager.
4.1 What is if elif else?
4.2 Grade Example
4.3 File Type Example
4.4 Life Stage Example
5. 🔗 Multiple Conditions
andis used when all conditions must be True. 📌 If even one condition is False, the whole and condition becomes False. Example:age = 25salary = 35000if age >= 21 and age <= 60 and salary >= 30000:print("You are eligible for loan.")else:print("You are not eligible for loan.")Output: You are eligible for loan.oris used when at least one condition must be True. 📌 If any one condition is True, the whole or condition becomes True. Example:day = "Saturday"if day == "Saturday" or day == "Sunday":print("It is weekend.")else:print("It is weekday.")Output: It is weekend.notis used to reverse the condition. Example:is_raining = Falseif not is_raining:print("You can go outside.")else:print("Take an umbrella.")Output: You can go outside.
5.1 Using and
5.2 Using or
5.3 Using not
6. 🧠 Nested if
- A nested if means an if statement inside another if statement. It is useful when one condition should be checked only after another condition is True.
Example:
age = 25salary = 35000if age >= 21:if salary >= 30000:print("You are eligible for loan.")else:print("Salary is too low.")else:print("Age is too low.")Output: You are eligible for loan. username = "admin"password = "1234"if username == "admin":if password == "1234":print("Login successful.")else:print("Wrong password.")else:print("Invalid username.")Output: Login successful.
6.1 What is Nested if?
6.2 Nested if Example with Login
7. ⚠️ Common Mistakes
- Wrong:
age = 18if age >= 18print("Adult")⚠️ This gives a SyntaxError because colon:is missing. 📌 SyntaxError means Python cannot understand the structure of the code. Correct:age = 18if age >= 18:print("Adult") - Wrong:
age = 18if age >= 18:print("Adult")⚠️ This gives an IndentationError becauseprintis not indented. Correct:age = 18if age >= 18:print("Adult") - Condition order matters in
if elif else. Wrong:marks = 85if marks >= 60:print("Grade: D")elif marks >= 80:print("Grade: B")Output: Grade: D Here,marks >= 60becomes True first, so Python does not checkmarks >= 80. Correct:marks = 85if marks >= 80:print("Grade: B")elif marks >= 60:print("Grade: D")Output: Grade: B
7.1 Missing Colon
7.2 Wrong Indentation
7.3 Wrong Condition Order
Practice QuestionsNot started
1. if else
Question 1 of 5
- Ask user for name and birth year. Calculate age and display voting eligibility in this format:
Ram, You are eligible for votingorRam, You are not eligible for voting. Rule: 18+ people can vote. - Ask user for
num_1andnum_2. Display whethernum_1is divisible bynum_2in this format:18 is divisible by 6or18 is not divisible by 6. Ifnum_2is 0, display: Cannot divide by zero. - Ask user for name, age, and salary. Display loan eligibility in this format:
Ram, You are eligible for loanorRam, You are not eligible for loan. Eligibility Rule: Age should be between 25 and 50, salary should be at least 50000. - Ask user for a string. Check whether it is a palindrome. Display output in this format:
madam is a palindromeormadam is not a palindrome - Store customer balance in a variable. Ask user for amount to withdraw. If withdraw amount is less than or equal to balance, display:
123 withdrawn successfully. New Balance: 456. Otherwise display:Insufficient balance. You only have 123 in your account
1.1 Practice if-else tasks:- Ask user for name and birth year. Calculate age and display voting eligibility in this format:
2. if elif else Ladder
Question 2 of 5
- Ask user for marks and display grade in this format:
Your grade is A. Rule: 90+ ➜ A, 80-89 ➜ B, 70-79 ➜ C, 60-69 ➜ D, Below 60 ➜ F - Ask user for birth year. Calculate age and display life stage in this format:
You are a teenager. Rule: 0-12 ➜ Child, 13-19 ➜ Teenager, 20-59 ➜ Adult, 60+ ➜ Senior - Ask user for three sides of a triangle. Display triangle type in this format:
This is an isosceles triangle. Rule: All sides equal ➜ Equilateral, Two sides equal ➜ Isosceles, No sides equal ➜ Scalene - Ask user for two numbers. Display the largest number in this format:
The largest number is 5 - Ask user for hour of the day from 0 to 23. Display appropriate greeting. Rule: 5-11 ➜ Good Morning, 12-16 ➜ Good Afternoon, 17-20 ➜ Good Evening, 21-23 ➜ Good Night, 0-4 ➜ Good Night, Else ➜ Invalid time
2.1 Practice if-elif-else tasks:- Ask user for marks and display grade in this format:
3. Multiple Conditions
Question 3 of 5
- Ask user for age and citizenship status. Display whether the person can vote. Rule: Age must be 18 or above, citizenship status must be "yes".
- Ask user for username and password. Display login result. Rule: Username should be "admin", password should be "1234".
- Ask user for marks and attendance percentage. Display whether the student is eligible for exam. Rule: Marks should be at least 40, attendance should be at least 75.
- Ask user for a number. Display whether the number is between 10 and 50.
- Ask user for day. Display whether it is weekend or weekday.
3.1 Practice tasks using multiple conditions:4. Nested if
Question 4 of 5
- Ask user for age and salary. Use nested if to check loan eligibility. Rule: First check age, then check salary.
- Ask user for username and password. Use nested if to display:
Login successful,Wrong password, orInvalid username - Ask user for marks. First check if marks are valid between 0 and 100. If valid, display pass or fail. Rule: 40 or above ➜ Pass, Below 40 ➜ Fail. If marks are outside 0 to 100, display:
Invalid marks
4.1 Practice nested if tasks:5. Challenge Questions
Question 5 of 5
- Ask user for electricity unit consumed. Calculate bill using: First 20 units ➜ Rs. 5 per unit. Units from 21 to 50 ➜ Rs. 7 per unit. Units above 50 ➜ Rs. 10 per unit. Display total bill.
- Ask user for year. Check whether it is a leap year. Rule: A year is leap year if divisible by 400, or divisible by 4 but not divisible by 100.
- Ask user for amount. Apply discount: Amount >= 10000 ➜ 20% discount, Amount >= 5000 ➜ 10% discount, Amount >= 2000 ➜ 5% discount, Below 2000 ➜ No discount. Display final amount after discount.
5.1 Practice challenge tasks:
