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

While Loops

Introduction

Welcome back to another Python tutorial! Today, we'll delve into the world of while loops. This essential control flow construct will help you write more dynamic and powerful code. By the end of this session, you'll be able to:
- Understand the role of while loops in Python programming
- Implement various use cases of while loops in your own projects

Core Concepts

A while loop allows a block of code to repeat as long as a specific condition is true. The general syntax looks like this:

while condition:
    # Code to be executed while the condition is true

The condition can be any expression that evaluates to a Boolean value (True or False). As long as the condition remains True, the code within the loop will continue to execute. Let's look at an example:

Example 1

Suppose we want to write a simple program that calculates the factorial of a number. For this, we can use a while loop and an accumulator variable to store the product:

n = 5
fact = 1
while n > 0:
    fact *= n
    n -= 1
print(fact) # Output: 120

In this example, we're using a while loop to repeatedly multiply the accumulator variable (fact) by the current value of n. We keep reducing n until it becomes zero, at which point the loop stops.

Practical Examples

Let's consider another practical use case for while loops: Guessing a secret number.

Example 2

Here's a simple game where the computer randomly selects a number between 1 and 100, and the player has to guess it within 6 attempts. We'll use a while loop to handle the guessing process:

import random
secret_number = random.randint(1, 100)
attempts = 0
guess = int(input("Guess a number between 1 and 100: "))
while attempts < 6:
    if guess == secret_number:
        print(f"Congratulations! You've guessed the secret number in {attempts + 1} attempts.")
        break
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print("Too low! Try again.")
    guess = int(input("Guess a number between 1 and 100: "))
    attempts += 1
if attempts == 6:
    print(f"You've run out of attempts. The secret number was {secret_number}.")

In this example, we use a while loop to repeatedly ask the player for their guess and provide feedback on whether it's too high or too low. If the player manages to guess the correct number before running out of attempts, the loop breaks using the break statement.

Common Issues and Solutions

NameError

What causes it:

while True:
    print(answer) # Undeclared variable 'answer'

Error message:

UnboundLocalError: local variable 'answer' referenced before assignment

Solution:

answer = None
while True:
    answer = input("Enter something: ")
    print(answer)

Why it happens: The error occurs because the variable answer is not defined before we try to access its value within the loop. To avoid this, make sure you initialize all variables before using them in a loop.

TypeError

What causes it:

while "apples" > "oranges":
    print("Apples are greater than oranges.") # Comparing strings as if they were numbers

Error message:

TypeError: '>=' not supported between instances of 'str' and 'str'

Solution:

while "apples" > "oranges" or "apples" < "oranges": # Use appropriate comparison operators for numbers or strings
    print("This is an error message.")

Why it happens: The > and < operators compare numbers, not strings. To fix this error, use the correct comparison operators (either >, <, ==, etc.) based on whether you're comparing numbers or strings.

Best Practices

  • Always initialize loop variables before using them in the condition
  • Use clear and meaningful variable names to improve readability
  • Break out of a loop when the desired condition is met using the break statement
  • Be aware of the differences between numerical and string comparisons

Key Takeaways

  • A while loop allows you to repeat a block of code as long as a specific condition is true
  • In a while loop, the condition should be carefully chosen to ensure that the loop terminates at some point
  • Use appropriate variable names and follow best practices to write clean and efficient code
  • Practice using while loops in various scenarios to solidify your understanding of this important control flow construct

As always, keep coding, learning, and having fun! See you next time.