Course Topics
Python Basics Introduction and Setup Syntax and Indentation Comments and Documentation Running Python Programs Exercise Variables and Data Types Variables and Assignment Numbers (int, float, complex) Strings and Operations Booleans and None Type Conversion Exercise Operators Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Bitwise Operators Exercise Input and Output Getting User Input Formatting Output Print Function Features Exercise Control Flow - Conditionals If Statements If-Else Statements Elif Statements Nested Conditionals Exercise Control Flow - Loops For Loops While Loops Loop Control (break, continue) Nested Loops Exercise Data Structures - Lists Creating and Accessing Lists List Methods and Operations List Slicing List Comprehensions Exercise Data Structures - Tuples Creating and Accessing Tuples Tuple Methods and Operations Tuple Packing and Unpacking Exercise Data Structures - Dictionaries Creating and Accessing Dictionaries Dictionary Methods and Operations Dictionary Comprehensions Exercise Data Structures - Sets Creating and Accessing Sets Set Methods and Operations Set Comprehensions Exercise Functions Defining Functions Function Parameters and Arguments Return Statements Scope and Variables Lambda Functions Exercise String Manipulation String Indexing and Slicing String Methods String Formatting Regular Expressions Basics Exercise File Handling Opening and Closing Files Reading from Files Writing to Files File Modes and Context Managers Exercise Error Handling Understanding Exceptions Try-Except Blocks Finally and Else Clauses Raising Custom Exceptions Exercise Object-Oriented Programming - Classes Introduction to OOP Creating Classes and Objects Instance Variables and Methods Constructor Method Exercise Object-Oriented Programming - Advanced Inheritance Method Overriding Class Variables and Methods Static Methods Exercise Modules and Packages Importing Modules Creating Custom Modules Python Standard Library Installing External Packages Exercise Working with APIs and JSON Making HTTP Requests JSON Data Handling Working with REST APIs Exercise Database Basics Introduction to Databases SQLite with Python CRUD Operations Exercise Final Project Project Planning Building Complete Application Code Organization Testing and Debugging Exercise

If-Else Statements

Introduction

Welcome back to our Python journey! Today we're going to delve into a fundamental aspect of programming that will help you make your code more dynamic and versatile: If-Else Statements. These statements enable us to create conditional logic in our programs, allowing them to react differently depending on certain conditions. Let's see what you'll learn today:

  • Understanding the purpose and syntax of If-Else Statements
  • Implementing simple If-Else Statements
  • Creating complex decision structures with nested If-Else statements
  • Debugging common issues that arise when working with If-Else Statements

Core Concepts

An If-Else Statement is a control flow structure that lets your code execute different blocks of code based on whether a given condition is true or false. It's made up of three main parts: the if, else, and optional elif statements. Here's a simple example:

age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

In this case, the condition is age >= 18. If it's true (i.e., age is equal to or greater than 18), then the code inside the if block will be executed (printing "You are an adult."). Otherwise, if the condition is false, the code inside the else block will be executed (printing "You are not an adult.").

The keyword elif allows you to create more complex conditions. For example:

age = 10

if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")

In this case, the code checks the conditions sequentially. First, it checks if age is greater than or equal to 18 (adult). If that's not true, then it moves on to check if age is greater than or equal to 13 (teenager). If neither of these conditions is met, it will execute the code inside the else block (child).

Practical Examples

Let's see how If-Else Statements can be used in real-world scenarios:

Example 1 - Grade Calculation

grade = int(input("Enter your grade (0-100): "))
if grade >= 90:
    print("Your grade is A.")
elif grade >= 80:
    print("Your grade is B.")
elif grade >= 70:
    print("Your grade is C.")
elif grade >= 60:
    print("Your grade is D.")
else:
    print("Your grade is F.")

This code calculates a student's grade based on their score.

Example 2 - Leap Year Determination

year = int(input("Enter a year (e.g., 2023): "))
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.")

This code determines whether a given year is a leap year.

Common Issues and Solutions

SyntaxError

What causes it: Incorrect indentation or syntax in the if-else structure.

if age >= 18:
   print("You are an adult.")
else:print("You are not an adult.")

Error message:

  File "example.py", line 2
    else:print("You are not an adult.")
            ^
SyntaxError: invalid syntax

Solution: Ensure proper indentation for both the if and else blocks.

Why it happens: Indentation is crucial in Python as it indicates the grouping of statements.

How to prevent it: Always use consistent indentation and ensure that all lines inside an if or else block are properly indented.

NameError

What causes it: Attempting to use a variable that has not been defined yet.

print(age)
if age >= 18:
    print("You are an adult.")

Error message:

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    print(age)
NameError: name 'age' is not defined

Solution: Define the variable before using it in the if-else statement.

Why it happens: Python does not automatically create variables for you, so any variable used must be defined prior to use.

How to prevent it: Always declare your variables before using them in your code.

TypeError

What causes it: Comparing different data types that cannot be compared directly (e.g., comparing a string with an integer).

if "10" > 5:
    print("10 is greater than 5.")

Error message:

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    if "10" > 5:
TypeError: unorderable types: str() > int()

Solution: Convert the data types to a common format before making the comparison (e.g., using int("10")).

Why it happens: Different data types have different comparison rules, and not all can be compared directly.

How to prevent it: Be mindful of the data types you're working with and ensure they can be compared directly or convert them to a common format if necessary.

Best Practices

  • Use descriptive variable names for clarity
  • Break down complex conditions into smaller parts using elif statements
  • Avoid unnecessary nesting of if-else statements when possible
  • Document your code with comments and clear naming conventions

Key Takeaways

  • If-Else Statements allow you to create conditional logic in your programs
  • Proper indentation is essential for the correct execution of if-else structures
  • Pay attention to data types and ensure they can be compared directly or converted to a common format
  • Follow best practices for clarity, maintainability, and performance

Now that you've learned about If-Else Statements, you can build more dynamic and versatile programs! As always, keep practicing and exploring new concepts. In our next lesson, we'll delve into loops, another essential aspect of programming in Python. Happy coding!