Python Loops: For and While Explained

Understand Python: LESSON 9 LOOPS IN PYTHON Imagine you want to print "Hello" 5x Without loops, we would do: print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") This is repetitive and inefficient. A loop enables Python to execute instructions repeatedly. ■ What Is a Loop? A loop is a programming structure that repeats a block of code until a condition is met. ■ Types of Loops in Python Python has two main loops: 1. for loop → used when the number of repetitions is known 2. while loop → used when the number of repetitions is unknown ■ The for Loop What Is a for Loop? A for loop is used to iterate over a sequence, such as: • List • String • Range of numbers Basic Syntax: for variable in sequence: # code to repeat Example 1: for i in range(5): print("Hello") Output: Hello Hello Hello Hello Hello 🔹 range(5) means numbers from 0 to 4 Example 2: for i in range(1, 6): print(i) Output: 1 2 3 4 5 ■ The while Loop What Is a while Loop? A while loop repeats as long as a condition is True. Basic Syntax: while condition: # code to repeat Example 1: count = 1 while count <= 5: print(count) count += 1 The count += 1 updates/increases the count value after each loop till it gets to 5 (while count <= 5) Output would be: 1, 2, 3, 4, 5 ⚠️ Always update the condition to avoid infinite loops. Example 2: password = "" while password != "1234": password = input("Enter password: ") print("Access granted") ■ Infinite Loops while True: print("This will run forever") Use this only when necessary, and always include a way to stop it. ■ Common Mistakes Beginners Make ❌ Forgetting to update the while condition ❌ Using wrong indentation ❌ Confusing for and while ❌ Creating infinite loops ■ When to Use Which Loop? • Known number of repetitions, use for loop • Unknown repetitions, use while loop • Looping through list/string, use for loop • Condition-based repetition, Use while loop #Python

  • No alternative text description for this image

Learning Python as a beginner doesn’t have to be confusing. I share simple, structured Python lessons and coding tips on my YouTube channel for people starting out in tech. 🎥 Subscribe here: https://youtube.com/@tonybenard7210?si=8R6opV3kZ_HDR242

Like
Reply

To view or add a comment, sign in

Explore content categories