Welcome back to CodeYourCraft! Today, we're diving into a fascinating aspect of Python programming: Loop Control Statements. These powerful tools help us automate repetitive tasks, making our code more efficient and our lives easier! šÆ
Imagine having to write the same line of code 100 times. Sounds exhausting, right? Loops let us write that line once, and the computer takes care of the rest. They're essential for dealing with collections of data, repeating actions, and much more! š
Python has two main types of loops: for loops and while loops. Let's explore them!
for loops are used when we want to iterate over a collection, like a list or a string. Here's a simple example:
# A list of fruits
fruits = ['apple', 'banana', 'orange']
# Iterate over the fruits
for fruit in fruits:
print(fruit)š” Pro Tip: for loops are great when you know the number of iterations beforehand.
while loops continue to execute as long as a certain condition is true. Here's a simple example:
# Initialize a counter
counter = 0
# Continue looping as long as counter is less than 5
while counter < 5:
print(counter)
counter += 1š” Pro Tip: while loops are useful when you don't know the number of iterations beforehand.
Sometimes, you might need to break out of a loop or skip iterations. Python provides break, continue, and pass statements for this purpose.
break stops the loop immediately. Here's an example:
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# Iterate over the numbers, but stop at 3
for number in numbers:
if number == 3:
break
print(number)continue skips the current iteration and continues with the next. Here's an example:
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# Print only even numbers
for number in numbers:
if number % 2 == 1:
continue
print(number)pass is a placeholder for when you want to write an empty statement, like when defining a loop skeleton. Here's an example:
# An empty for loop
for _ in range(5):
passWhat does the `break` statement do in Python?
Now that you've learned about loop control statements, you're one step closer to mastering Python! Remember, practice makes perfect. Keep coding and exploring, and you'll soon be creating amazing projects with ease! ā
Stay tuned for more exciting topics in our Python Tutorial series here at CodeYourCraft! š