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 Statements

Introduction

Welcome to the exciting world of conditional statements in Python! In this lesson, we'll learn how to make your code more dynamic and responsive with if statements. By the end of this tutorial, you'll be able to write cleaner, more efficient scripts that adjust their behavior based on various conditions.

Core Concepts

An if statement allows us to execute a block of code only when certain conditions are met. The basic structure is as follows:

if condition:
    # Code executed if the condition is true
else:
    # Code executed if the condition is false (optional)

The condition can be any expression that evaluates to a boolean value (True or False). Here's an example:

age = 18
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You must wait until you turn 18 to vote.")

Practical Examples

Let's consider a simple example where we ask the user for their age and display a message based on whether they are eligible to drive or not.

age = int(input("Enter your age: "))
if age >= 16:
    if age < 18:
        print("You can get a learner's permit.")
    else:
        print("Congratulations, you can now drive!")
else:
    print("Sorry, you are too young to drive.")

Common Issues and Solutions

NameError

What causes it:

print(color)  # Assuming the variable color has not been defined yet.

Error message:

NameError: name 'color' is not defined

Solution:

color = "blue"
print(color)

Why it happens:

The interpreter does not know about the variable until it has been assigned a value.

How to prevent it:

Make sure to define all variables before using them in your code.

TypeError

What causes it:

if "5":  # Comparing a string with an integer leads to a TypeError.
    print("This should not happen.")

Error message:

TypeError: unorderable types: str() < int()

Solution:

if int("5"):  # Converting the string to an integer before comparison.
    print("This should not happen.")

Why it happens:

Python cannot compare strings and integers directly due to their different data types.

How to prevent it:

Ensure that the operands being compared have compatible data types or convert them as needed before comparison.

IndentationError

What causes it:

if True:
print("Hello")  # Missing a colon at the end of the if statement.

Error message:

IndentationError: expected an indented block

Solution:

if True:
    print("Hello")

Why it happens:

Python uses indentation to determine code blocks, and a missing colon will cause the interpreter to be confused about where the block starts.

How to prevent it:

Always include colons at the end of if, for, and while statements, followed by properly indented lines of code below them.

Best Practices

  • Use clear and descriptive conditions in your if statements.
  • Consider using multiple elif clauses to handle different possibilities within a single condition block.
  • Keep your code organized and easy to read by using consistent indentation and meaningful variable names.
  • Always test your conditions with both True and False values to ensure they behave as intended.

Key Takeaways

In this lesson, we learned about the if statement in Python, explored practical examples, and discussed common issues and solutions. By mastering conditional statements, you'll be able to write more flexible and adaptable code that can handle a variety of scenarios. As you continue your programming journey, remember to practice good coding habits and always strive for clarity and readability in your scripts.

Now, go forth and conquer the world with your newfound knowledge! Happy coding! 🤓🚀