This chapter covers part of Python control flow statements, which dictate the order in which individual statements or instructions are executed in a program. They allow your code to make decisions, repeat actions, and respond dynamically to different conditions.
-
Conditional Statements Explanation: Conditional statements in Python allow your program to execute different blocks of code based on whether certain conditions are
TrueorFalse. This introduces decision-making into your Python scripts, making them dynamic and responsive.-
ifstatement-
Explanation: The
ifstatement is the most basic Python conditional statement. It executes a block of code only if its condition evaluates toTrue. If the condition isFalse, the indented code block is skipped. -
Syntax:
if condition: # Code to execute if condition is True -
Note:
python if statement tutorial,basic if condition python,python conditional logic,if block python,decision making in python. -
Code Examples:
# Example 1 (Beginner-Friendly): Simple if statement with a number # Checks if a number is positive. If true, prints a message. number = 10 if number > 0: print(f"The number {number} is positive.") # Example 2 (Slightly More Complex): if statement with a string # Checks for a specific string value. Case-sensitivity matters. user_choice = "start" if user_choice == "start": print("Starting the application...") # Example 3 (Intermediate): if statement with boolean variable (direct use) # Often, the result of a comparison or logical operation is directly used. is_logged_in = True if is_logged_in: print("Welcome back! Accessing user dashboard.") # Example 4 (Advanced Beginner): if with truthy/falsy values # Python evaluates non-boolean objects as True or False in a boolean context. # An empty list is Falsy, a non-empty list is Truthy. my_list = [1, 2, 3] # This is a "truthy" value if my_list: print(f"The list is not empty. It contains {len(my_list)} items.") empty_data = "" # This is a "falsy" value if not empty_data: # 'not' empty_data means if it's falsy (e.g., empty string) print("No data received.") # Example 5 (Intermediate): if with a complex condition (logical operators) # Combines multiple conditions using 'and' and 'or' for more specific checks. temperature = 28 is_raining = False if temperature > 25 and not is_raining: print("It's a hot and dry day! Perfect for outdoor activities.") # Example 6 (Advanced): if based on function return value # The condition can be the result of a function call. def check_status(user_id): # In a real app, this would query a database or API if user_id == "admin123": return True return False current_user_id = "admin123" if check_status(current_user_id): print(f"User {current_user_id} has administrative privileges.") # Example 7 (Advanced): if with an object's attribute # Checking a property or state of an object. class Door: def __init__(self, is_open): self.is_open = is_open front_door = Door(True) if front_door.is_open: print("The front door is open.") -
-
if-elsestatement-
Explanation: The
if-elsestatement provides two possible execution paths. The code block underifis executed if the condition isTrue. If the condition isFalse, the code block underelseis executed. This ensures that one of two actions will always occur based on the condition. -
Syntax:
if condition: # Code to execute if condition is True else: # Code to execute if condition is False -
Note:
python if else example,if else statement python,python true false conditions,two way decision python,else block python. -
Code Examples:
# Example 1 (Beginner-Friendly): Simple even/odd check # Determines if a number is even or odd using the modulo operator. num = 7 if num % 2 == 0: print(f"{num} is an even number.") else: print(f"{num} is an odd number.") # Example 2 (Slightly More Complex): Checking user age for access # A common use case for access control based on a condition. user_age = 17 if user_age >= 18: print("Access granted: You are an adult.") else: print("Access denied: You must be 18 or older.") # Example 3 (Intermediate): Login success/failure # Simulating a login attempt based on a boolean outcome. username_attempt = "admin" password_attempt = "wrong_pass" correct_username = "admin" correct_password = "secure_pass" if username_attempt == correct_username and password_attempt == correct_password: print("Login successful! Welcome.") else: print("Login failed. Invalid username or password.") # Example 4 (Advanced Beginner): Handling empty input (revisited with else) # Provides a clear alternative path when input is missing. user_input_text = input("Please type something: ") if user_input_text: # Checks if the string is not empty (is truthy) print(f"You typed: '{user_input_text}'") else: print("You didn't type anything.") # Example 5 (Intermediate): Function with if-else returning different values # Functions often use if-else to return different results based on input. def get_ticket_price(is_student, age): if is_student or age < 12: # Student or child gets a discount return 5.00 else: return 10.00 # Regular price price1 = get_ticket_price(True, 20) # Student price2 = get_ticket_price(False, 8) # Child price3 = get_ticket_price(False, 30) # Adult print(f"Ticket price for student (20): ${price1:.2f}") print(f"Ticket price for child (8): ${price2:.2f}") print(f"Ticket price for adult (30): ${price3:.2f}") # Example 6 (Advanced): if-else with file existence check # Checking for resources before attempting to use them. import os file_name = "my_data.txt" if os.path.exists(file_name): print(f"'{file_name}' exists. Proceeding to read content.") # In a real scenario, you'd open and read the file here. else: print(f"'{file_name}' does not exist. Creating a new file.") with open(file_name, 'w') as f: f.write("This is new data.\n") print(f"'{file_name}' created successfully.") # Example 7 (Advanced): Ternary Operator (Conditional Expression) # A concise way to write a simple if-else statement on a single line. # Syntax: value_if_true if condition else value_if_false status = "Active" if user_age >= 18 else "Inactive" print(f"User status: {status}") max_val = num1 if num1 > num2 else num2 print(f"Maximum value between {num1} and {num2} is: {max_val}") -
-
if-elif-elseladder-
Explanation: The
if-elif-else(short for "else if") statement allows you to test multiple conditions sequentially. Python checks theifcondition first. IfTrue, its block executes, and the rest of the ladder is skipped. IfFalse, it moves to the firstelifcondition. This continues down theelifstatements. If none of theiforelifconditions areTrue, theelseblock (if present) is executed. This is ideal for scenarios with more than two possible outcomes based on different criteria. -
Syntax:
if condition1: # Code if condition1 is True elif condition2: # Code if condition1 is False, and condition2 is True elif condition3: # Code if condition1 and condition2 are False, and condition3 is True else: # Code if all above conditions are False -
Note:
python if elif else,multiple conditions python,chained if statements python,python grade system,multi-way decision python. -
Code Examples:
# Example 1 (Beginner-Friendly): Grading system # A classic use case for if-elif-else to assign grades based on a score range. score = 85 if score >= 90: grade = "A" elif score >= 80: # This is checked only if score < 90 grade = "B" elif score >= 70: # This is checked only if score < 80 grade = "C" elif score >= 60: # This is checked only if score < 70 grade = "D" else: # This is executed if score < 60 grade = "F" print(f"With a score of {score}, the grade is: {grade}") # Example 2 (Slightly More Complex): Traffic light simulation # Simulating states of a traffic light. light_color = "yellow" if light_color == "green": print("Traffic light is green. Go!") elif light_color == "yellow": print("Traffic light is yellow. Prepare to stop.") elif light_color == "red": print("Traffic light is red. Stop!") else: print("Invalid light color detected.") # Example 3 (Intermediate): Categorizing numbers # Classifying a number as positive, negative, or zero. value = -5 if value > 0: category = "Positive" elif value < 0: category = "Negative" else: category = "Zero" print(f"The value {value} is: {category}") # Example 4 (Advanced Beginner): User role management # Assigning different permissions or actions based on user roles. user_role = "editor" if user_role == "admin": print("Full access: Create, Read, Update, Delete all content.") elif user_role == "editor": print("Limited access: Create, Read, Update own content.") elif user_role == "viewer": print("Read-only access.") else: print("Unknown role. No access.") # Example 5 (Intermediate): Complex decision tree in a function # A function deciding a recommendation based on multiple factors. def get_movie_recommendation(genre, rating, duration_minutes): if genre == "Action" and rating >= 7.0: return "High-octane Action Thriller!" elif genre == "Comedy" and duration_minutes <= 100: return "Light and Funny Comedy!" elif genre == "Drama" and rating >= 8.0: return "Award-winning Drama!" else: return "Consider something else or try another genre!" print(f"Recommendation 1: {get_movie_recommendation('Action', 7.5, 120)}") print(f"Recommendation 2: {get_movie_recommendation('Comedy', 6.0, 95)}") print(f"Recommendation 3: {get_movie_recommendation('Horror', 7.0, 150)}") # Will fall to else # Example 6 (Advanced): Using if-elif-else with user input and type conversion # Combines user input, error handling for type conversion, and conditional logic. try: temp_input = input("Enter temperature (in Celsius): ") temperature = float(temp_input) if temperature < 0: print("It's freezing! Stay warm.") elif 0 <= temperature < 10: print("It's quite cold. Grab a jacket.") elif 10 <= temperature < 20: print("The weather is mild.") elif 20 <= temperature < 30: print("It's warm and pleasant.") else: # temperature >= 30 print("It's hot! Hydrate well.") except ValueError: print("Invalid temperature. Please enter a numeric value.") # Example 7 (Advanced): If-elif-else with multiple conditions and short-circuiting # Demonstrating how the order of `elif` matters due to short-circuiting. # The most specific or common conditions should often come first. age = 68 is_student = True is_veteran = False if age < 12: print("Child discount applied.") elif age >= 65 and not is_student: # Elderly discount (if not also a student for a potentially different discount) print("Senior citizen discount applied.") elif is_student: # Student discount (after checking child and non-student senior) print("Student discount applied.") elif is_veteran: print("Veteran discount applied.") else: print("No special discount applied.") -
-
Nested
ifstatements-
Explanation: Nested
ifstatements occur when oneif(oreliforelse) block contains anotherifstatement (or another conditional ladder). This allows for very specific decision-making based on multiple layers of conditions. While powerful, deeply nestedifstatements can sometimes make code harder to read and maintain, so they should be used judiciously. -
Syntax:
if outer_condition: # Code for outer condition is True if inner_condition1: # Code if inner_condition1 is True else: # Code if inner_condition1 is False else: # Code if outer_condition is False -
Note:
python nested if else,if inside if python,multi-level conditions python,complex conditional logic python,nested decision making python. -
Code Examples:
# Example 1 (Beginner-Friendly): Basic nested if # Checks an outer condition, then an inner condition. weather = "sunny" temperature = 28 if weather == "sunny": print("It's a sunny day!") if temperature > 25: print("It's also quite hot!") else: print("The temperature is pleasant.") else: print("It's not sunny today.") # Example 2 (Slightly More Complex): User authentication and authorization # Checks if login is successful, then checks user role for access. logged_in = True user_role = "admin" if logged_in: print("User is logged in.") if user_role == "admin": print("Granting administrative access.") elif user_role == "editor": print("Granting editorial access.") else: print("Granting basic user access.") else: print("User is not logged in. Please authenticate.") # Example 3 (Intermediate): Order processing with stock and credit check # Simulates checking inventory and then customer credit. item_in_stock = True customer_has_credit = True order_amount = 150 if item_in_stock: print("Item is available in stock.") if customer_has_credit: if order_amount <= 200: # Nested check for order limit print("Order approved and being processed.") else: print("Order amount exceeds credit limit. Approval needed.") else: print("Customer does not have sufficient credit.") else: print("Item is out of stock. Cannot process order.") # Example 4 (Advanced Beginner): Nested if for a game scenario # Deciding outcome in a simple text adventure. player_location = "forest" has_key = True if player_location == "forest": print("You are in a dense forest.") action = input("Do you go 'north' or 'south'? ").lower() if action == "north": print("You found a hidden cave!") if has_key: print("You unlock the ancient door with your key!") else: print("The door is locked. You need a key.") elif action == "south": print("You encounter a raging river. You cannot cross.") else: print("Invalid direction.") else: print("You are not in the forest.") # Example 5 (Intermediate): Nested if with multiple 'elif' branches # A more complex grading scenario that checks for multiple conditions within. student_score = 92 attendance_rate = 0.95 # 95% attendance if student_score >= 90: if attendance_rate >= 0.90: # High score AND good attendance print("Excellent! Grade A+ (High Attendance Bonus)") else: print("Excellent! Grade A (Attendance deducted from A+)") elif student_score >= 80: if attendance_rate >= 0.80: print("Very Good! Grade B") else: print("Good, but attendance needs improvement. Grade C.") else: print("Further study required. Grade F.") # Example 6 (Advanced): Nested if for parsing complex configuration # Simulating parsing options where outer option dictates inner options. config_mode = "network" network_type = "wifi" security_level = "WPA2" if config_mode == "network": print("Configuring network settings:") if network_type == "ethernet": print(" Ethernet connection selected.") connection_speed = input(" Enter desired speed (100Mbps/1Gbps): ") if connection_speed == "1Gbps": print(" Gigabit Ethernet configured.") else: print(" Standard Ethernet configured.") elif network_type == "wifi": print(" Wi-Fi connection selected.") if security_level == "WPA2": print(" WPA2 security enabled.") elif security_level == "WPA3": print(" WPA3 security enabled (advanced).") else: print(" No/Weak security. Warning!") else: print(" Unknown network type.") elif config_mode == "display": print("Configuring display settings...") else: print("Unknown configuration mode.") # Example 7 (Advanced): Using nested if for data validation in a function # A function to validate user registration data. def validate_registration(username, password, email): if len(username) >= 5: if len(password) >= 8: if "@" in email and "." in email: # Simple email format check return True, "Registration successful!" else: return False, "Invalid email format." else: return False, "Password must be at least 8 characters long." else: return False, "Username must be at least 5 characters long." status, message = validate_registration("user123", "pass123", "test@example.com") print(f"Validation 1: {message} (Success: {status})") status, message = validate_registration("john", "short", "john@mail.com") print(f"Validation 2: {message} (Success: {status})") -
-