Loops allow you to repeat a block of code multiple times without rewriting it. This makes your program more efficient and scalable. For example, if you want to print all items in a list or keep checking user input until it's valid, loops are the perfect tool.
Python has two main types of loops:
for loops, which iterate over sequencewhile loops, which repeat while a condition is true.The for loop in Python is used to iterate over a sequence like a list, string, or range of numbers. Each iteration allows you to perform actions on the current item.
for item in sequence:
# do somethingThe variable after for (like i or name) changes each time through the loop. It takes on each value from the sequence.
The while loop continues to run as long as its condition remains true. It's useful when the number of iterations isn't predetermined, like reading input until a user enters "quit".
A while loop is used to repeat a block of code as long as a given condition is True. It’s useful when the number of repetitions isn’t known ahead of time.
The loop checks the condition before each iteration. If the condition becomes False, the loop stops.
while condition:
# code to repeatbreak lets you exit a loop early when a condition is met.continue skips the current loop iteration and proceeds to the next one.
A nested loop is a loop placed inside another loop. In Python, you can nest for loops, while loops, or a combination of both.
The inner loop runs completely every time the outer loop runs once. Nested loops are useful for working with grids, matrices, or repeated patterns.
This example prints all combinations of i and j from 1 to 3.
Write a for loop that prints each letter in the string "Python" on its own line.
Expected Output:
P y t h o n
Ask the AI if you need help understanding or want to dive deeper in any topic