Conditional Statements

1. 🚦 Conditional Statements

    1.1 What are Conditional Statements?
    1. 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.
    1.2 Boolean Conditions
    1. A condition is an expression that gives either True or False. Examples: print(10 > 5) # ➜ True print(10 < 5) # ➜ False print(18 >= 18) # ➜ True print("pdf" == "pdf") # ➜ True 📌 if statements use these True or False results to decide which code block to run.
    1.3 Indentation
    1. 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 the if block because it is indented. ⚠️ If indentation is wrong, Python gives an IndentationError. 📌 Code inside if, elif, and else must be properly indented.

2. ✅ if Statement

    2.1 What is if?
    1. if is 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.
    2.2 if Example with Number
    1. num = 10if num > 0:print("Number is positive.")Output: Number is positive.
    2.3 if Example with String
    1. file_name = "report.pdf"if file_name.endswith(".pdf"):print("This is a PDF file.")Output: This is a PDF file.

3. 🔀 if else Statement

    3.1 What is if else?
    1. if else is 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 True else: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.
    3.2 Voting Example
    1. age = 18if age >= 18:print("You are eligible for voting.") else:print("You are not eligible for voting.")Output: You are eligible for voting.
    3.3 Divisibility Example
    1. num_1 = 15 num_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

4. 🪜 if elif else Ladder

    4.1 What is if elif else?
    1. if elif else is 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 True elif condition_2:code to run if condition_2 is True elif condition_3:code to run if condition_3 is True else:code to run if none of the above conditions are True 📌 elif means else if. 📌 We can use multiple elif blocks. 📌 else is optional.
    4.2 Grade Example
    1. 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 condition marks >= 80 becomes True.
    4.3 File Type Example
    1. 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.
    4.4 Life Stage Example
    1. 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.

5. 🔗 Multiple Conditions

    5.1 Using and
    1. and is used when all conditions must be True. 📌 If even one condition is False, the whole and condition becomes False. Example: age = 25 salary = 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.
    5.2 Using or
    1. or is 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.
    5.3 Using not
    1. not is 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.

6. 🧠 Nested if

    6.1 What is Nested if?
    1. 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 = 25 salary = 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.
    6.2 Nested if Example with Login
    1. username = "admin" password = "1234"if username == "admin":if password == "1234":print("Login successful.")else:print("Wrong password.") else:print("Invalid username.")Output: Login successful.

7. ⚠️ Common Mistakes

    7.1 Missing Colon
    1. 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")
    7.2 Wrong Indentation
    1. Wrong: age = 18if age >= 18: print("Adult") ⚠️ This gives an IndentationError because print is not indented. Correct: age = 18if age >= 18:print("Adult")
    7.3 Wrong Condition Order
    1. 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 >= 60 becomes True first, so Python does not check marks >= 80. Correct: marks = 85if marks >= 80:print("Grade: B") elif marks >= 60:print("Grade: D")Output: Grade: B

Practice QuestionsNot started

  1. 1. if else

    Question 1 of 5

      1.1 Practice if-else tasks:
      1. Ask user for name and birth year. Calculate age and display voting eligibility in this format: Ram, You are eligible for voting or Ram, You are not eligible for voting. Rule: 18+ people can vote.
      2. Ask user for num_1 and num_2. Display whether num_1 is divisible by num_2 in this format: 18 is divisible by 6 or 18 is not divisible by 6. If num_2 is 0, display: Cannot divide by zero.
      3. Ask user for name, age, and salary. Display loan eligibility in this format: Ram, You are eligible for loan or Ram, You are not eligible for loan. Eligibility Rule: Age should be between 25 and 50, salary should be at least 50000.
      4. Ask user for a string. Check whether it is a palindrome. Display output in this format: madam is a palindrome or madam is not a palindrome
      5. 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
  2. 2. if elif else Ladder

    Question 2 of 5

      2.1 Practice if-elif-else tasks:
      1. 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
      2. 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
      3. 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
      4. Ask user for two numbers. Display the largest number in this format: The largest number is 5
      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
  3. 3. Multiple Conditions

    Question 3 of 5

      3.1 Practice tasks using multiple conditions:
      1. 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".
      2. Ask user for username and password. Display login result. Rule: Username should be "admin", password should be "1234".
      3. 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.
      4. Ask user for a number. Display whether the number is between 10 and 50.
      5. Ask user for day. Display whether it is weekend or weekday.
  4. 4. Nested if

    Question 4 of 5

      4.1 Practice nested if tasks:
      1. Ask user for age and salary. Use nested if to check loan eligibility. Rule: First check age, then check salary.
      2. Ask user for username and password. Use nested if to display: Login successful, Wrong password, or Invalid username
      3. 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
  5. 5. Challenge Questions

    Question 5 of 5

      5.1 Practice challenge tasks:
      1. 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.
      2. 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.
      3. 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.