Class 08 & 09 Conditional Statements

Conditional Statements in Python ๐Ÿšฆ

Conditional statements in Python allow your program to make decisions based on specific conditions. Here’s a comprehensive overview:


1. if Statement โœ…

Executes a block of code only if a condition is True.

Python

age = 18
if age >= 18:
    print("You are eligible to vote")

2. if-else Statement โ“

Adds an alternative path when the if condition is False.

Python

temperature = 30
if temperature > 25:
    print("It's hot outside")
else:
    print("It's cool outside")

3. if-elif-else Statement ๐Ÿชœ

Handles multiple conditions sequentially. The first true condition executes its block.

Python

score = 85
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'  # This block executes
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'
print(f"Your grade is {grade}")  # Output: B

4. Nested Conditionals ๐Ÿงฉ

if statements inside other if statements.

Python

num = 10
if num > 0:
    if num % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")
else:
    print("Non-positive number")

5. Ternary Operator โ“โžก๏ธ

A concise one-line expression for simple if-else logic.

Python

is_rainy = True
activity = "Stay indoors" if is_rainy else "Go hiking"
print(activity)  # Output: Stay indoors

6. Logical Operators (and, or, not) ๐Ÿค

Combine multiple conditions:

Python

age = 25
has_license = True
if age >= 18 and has_license:
    print("You can drive")  # Executes

7. Truthiness Checks ๐Ÿ’ก

Non-boolean values are evaluated as True (non-zero, non-empty) or False (zero, empty, None).

Python

name = ""
if not name:  # Checks if name is empty
    print("Name is required")

Key Rules: ๐Ÿ“œ

  • Colon and Indentation: Always end conditions with : and indent code blocks. โžก๏ธPythonif condition: # Colon required ... # Indentation (4 spaces)
  • Execution Flow: Conditions are checked top-to-bottom. The first true condition triggers its block and exits the structure. โฌ‡๏ธ
  • else is Optional: Use when you need a default action. ๐Ÿคท
  • Parentheses: Optional for simple conditions but improve readability for complex logic. ()Pythonif (age > 12) and (age < 20): print("Teenager")

Example: User Authentication ๐Ÿ”’

Python

username = "admin"
password = "secret123"

if username == "admin" and password == "secret123":
    print("Access granted")
elif username == "admin":
    print("Wrong password")
else:
    print("Invalid username")

Common Use Cases: ๐ŸŽฏ

  • Validating user input โœ…
  • Controlling program flow โžก๏ธ
  • Error handling ๐Ÿ›ก๏ธ
  • Feature toggling based on conditions ๐Ÿ’ก

1. Number Sign Checker

Checks if a number is positive, negative, or zero.

python

num = float(input("Enter a number: "))
if num > 0:
    print("Positive number")
elif num < 0:
    print("Negative number")
else:
    print("Zero")

2. Voting Eligibility

Determines if a person is eligible to vote.

python

age = int(input("Enter your age: "))
if age >= 18:
    print("You can vote!")
else:
    years_left = 18 - age
    print(f"Wait {years_left} more year(s) to vote")

3. Leap Year Checker

Checks if a year is a leap year.

python

year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")

4. Simple Calculator

Performs basic arithmetic operations.

python

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Choose operation (+, -, *, /): ")

if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
result = num1 / num2 if num2 != 0 else "Error! Division by zero"
else:
result = "Invalid operation"

print(f"Result: {result}")

Conditional Statement Examples ๐Ÿšฆ


1. Vowel or Consonant Checker ๐Ÿ—ฃ๏ธ

Checks if a character is a vowel or consonant:

Python

char = input("Enter a character: ").lower()
if char in 'aeiou':
    print(f"{char} is a vowel")
elif char.isalpha():
    print(f"{char} is a consonant")
else:
    print("Invalid input - please enter an alphabet character")

2. Discounted Bill Calculator ๐Ÿ’ธ

Applies discounts based on purchase amount:

Python

amount = float(input("Enter purchase amount: $"))
if amount > 1000:
    discount = 0.20
elif amount > 500:
    discount = 0.15
elif amount > 200:
    discount = 0.10
else:
    discount = 0

final_amount = amount - (amount * discount)
print(f"Discount: {discount*100}% | Final amount: ${final_amount:.2f}")

3. Month Number to Name Converter ๐Ÿ“…

Converts month number to month name:

Python

month_num = int(input("Enter month number (1-12): "))
if month_num == 1:
    print("January")
elif month_num == 2:
    print("February")
elif month_num == 3:
    print("March")
elif month_num == 4:
    print("April")
elif month_num == 5:
    print("May")
elif month_num == 6:
    print("June")
elif month_num == 7:
    print("July")
elif month_num == 8:
    print("August")
elif month_num == 9:
    print("September")
elif month_num == 10:
    print("October")
elif month_num == 11:
    print("November")
elif month_num == 12:
    print("December")
else:
    print("Invalid month number. Please enter 1-12.")

4. Day Number to Name Converter ๐Ÿ—“๏ธ

Converts day number to day name (Monday=1 to Sunday=7):

Python

day_num = int(input("Enter day number (1-7): "))
if day_num == 1:
    print("Monday")
elif day_num == 2:
    print("Tuesday")
elif day_num == 3:
    print("Wednesday")
elif day_num == 4:
    print("Thursday")
elif day_num == 5:
    print("Friday")
elif day_num == 6:
    print("Saturday")
elif day_num == 7:
    print("Sunday")
else:
    print("Invalid day number. Please enter 1-7.")

5. Temperature Category Classifier ๐ŸŒก๏ธ

Classifies temperature into categories:

Python

temp = float(input("Enter temperature in ยฐC: "))
if temp > 40:
    print("Extreme Heat")
elif temp > 30:
    print("Hot")
elif temp > 20:
    print("Warm")
elif temp > 10:
    print("Cool")
elif temp > 0:
    print("Cold")
else:
    print("Freezing")

Similar Posts

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

  • Various types of data types in python

    ๐Ÿ”ข Numeric Types Used for storing numbers: ๐Ÿ”ก Text Type Used for textual data: ๐Ÿ“ฆ Sequence Types Ordered collections: ๐Ÿ”‘ Mapping Type Used for key-value pairs: ๐Ÿงฎ Set Types Collections of unique elements: โœ… Boolean Type ๐Ÿช™ Binary Types Used to handle binary data: Want to explore examples of each, or dive deeper into when…

  • Mutable vs. Immutable Objects in Python ๐Ÿ”„๐Ÿ”’

    Mutable vs. Immutable Objects in Python ๐Ÿ”„๐Ÿ”’ In Python, mutability determines whether an object’s value can be changed after creation. This is crucial for understanding how variables behave. ๐Ÿค” Immutable Objects ๐Ÿ”’ Example 1: Strings (Immutable) ๐Ÿ’ฌ Python Example 2: Tuples (Immutable) ๐Ÿ“ฆ Python Mutable Objects ๐Ÿ“ Example 1: Lists (Mutable) ๐Ÿ“‹ Python Example 2:…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability โ™ป๏ธ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

Leave a Reply

Your email address will not be published. Required fields are marked *