whenever life put's you in a tough situtation, never say why me! but, try me!

Control Flow: Conditional Statements in Python

Control flow allows the program to execute specific blocks of code based on certain conditions. Conditional statements are used to make decisions in your code, allowing different actions to be performed based on different conditions.


Subtopic 1: Introduction to Control Flow

In Python, control flow is managed using conditional statements, loops, and exception handling. Conditional statements allow us to control which block of code is executed based on specific conditions, such as comparisons or boolean expressions.

The basic conditional statements in Python are:

  • if
  • elif (short for "else if")
  • else

These statements are used to decide whether a certain condition or set of conditions are true or false, and then execute corresponding code.


Subtopic 2: If, Elif, Else Statements

The if, elif, and else statements are used to execute specific blocks of code based on conditions.

Syntax
if condition1:
    # Code block executed if condition1 is True
elif condition2:
    # Code block executed if condition1 is False and condition2 is True
else:
    # Code block executed if neither condition1 nor condition2 is True
Example
# Example of if-elif-else
age = 18

if age < 18:
    print("You are a minor.")
elif age == 18:
    print("You are an adult now!")
else:
    print("You are an adult.")

Output:

You are an adult now!
Explanation:
  • The if block checks if the age is less than 18, and if true, it prints "You are a minor."
  • The elif block checks if the age is exactly 18, and prints "You are an adult now!"
  • If none of the conditions are true, the else block is executed.

Subtopic 3: Nested Conditions

In some cases, you may need to use conditions inside other conditions, which is called nested conditions. This allows you to check multiple conditions within each branch of the code.

Syntax
if condition1:
    if condition2:
        # Execute this block if both condition1 and condition2 are True
    else:
        # Execute this block if condition1 is True but condition2 is False
else:
    # Execute this block if condition1 is False
Example
# Example of nested if-else
temperature = 30

if temperature > 25:
    if temperature > 35:
        print("It's too hot!")
    else:
        print("It's warm outside.")
else:
    print("It's cool outside.")

Output:

It's warm outside.

Explanation:

  • First, the outer if checks if the temperature is greater than 25. If true, it checks the inner if.
  • If the temperature is greater than 35, it prints "It's too hot!". Otherwise, it prints "It's warm outside."
  • If the temperature is not greater than 25, it moves to the else block, printing "It's cool outside."

Subtopic 4: Ternary Operators in Python

Ternary operators allow you to write simple conditional statements in a single line. The basic syntax for a ternary operator in Python is:

value_if_true if condition else value_if_false

This is a shorter and more readable way of expressing simple if-else conditions.

Example
# Example of ternary operator
age = 18

status = "Adult" if age >= 18 else "Minor"
print(status)

Output:

Adult

Explanation:

  • The expression "Adult" if age >= 18 else "Minor" checks the condition age >= 18.
  • If the condition is True, the expression returns "Adult", otherwise it returns "Minor".
  • In this case, age is 18, so the result is "Adult".

Tasks

  1. Task 1: Check if a number is positive, negative, or zero.

    • Write a Python program that accepts a number and prints whether the number is positive, negative, or zero.
    num = int(input("Enter a number: "))
    
    if num > 0:
        print("The number is positive.")
    elif num < 0:
        print("The number is negative.")
    else:
        print("The number is zero.")
    
  2. Task 2: Determine if a year is a leap year.

    • Write a program to check if a year is a leap year. A year is a leap year if:
      • It is divisible by 4.
      • It is not divisible by 100 unless it is also divisible by 400.
    year = int(input("Enter a 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.")
    
  3. Task 3: Create a simple grade calculator.

    • Write a program to input a student's marks and output their grade based on the following criteria:
      • 90 or above: "A"
      • 70 to 89: "B"
      • 50 to 69: "C"
      • Below 50: "Fail"
    marks = int(input("Enter your marks: "))
    
    if marks >= 90:
        print("Grade: A")
    elif marks >= 70:
        print("Grade: B")
    elif marks >= 50:
        print("Grade: C")
    else:
        print("Grade: Fail")
    
  4. Task 4: Determine if a number is even or odd.

    • Write a Python program that checks whether a given number is even or odd.
    num = int(input("Enter a number: "))
    
    if num % 2 == 0:
        print(f"{num} is even.")
    else:
        print(f"{num} is odd.")
    
  5. Task 5: Determine the largest of three numbers.

    • Write a program that takes three numbers as input and prints the largest one.
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    num3 = int(input("Enter the third number: "))
    
    if num1 >= num2 and num1 >= num3:
        print(f"The largest number is {num1}")
    elif num2 >= num1 and num2 >= num3:
        print(f"The largest number is {num2}")
    else:
        print(f"The largest number is {num3}")