Learn Python in 30 Days — Day 8: For Loops
Learn Python in 30 Days — Day 8: For Loops
Welcome to Day 8 of the Learn Python in 30 Days series!
All example files for this series are available on my GitHub: Learn-Python-in-30-Days
Yesterday you finished Week 1 by reviewing what you’ve learned so far.
Today begins Week 2: Loops & Collections, where you’ll learn how to make your code repeat itself automatically another key part of programming.
By the end of this lesson, you’ll understand:
-
What a for loop is and how it works
-
How to loop through ranges, lists, and strings
-
How to use the
range()function effectively -
How to combine loops with logic for practical tasks
Step 1 – What Is a For Loop?
A for loop is used to iterate, to repeat something for each item in a sequence.
Think of it as saying:
“For each item in this group, do this action.”
Example:
This prints “Hello, world!” five times because range(5) gives the numbers 0, 1, 2, 3, 4.
Try typing this into the IDLE IDE and running it and you should see the following output.
You can also download this example from my GitHub here and run it yourself.
Step 2 – Looping Through a Range
You can use range(start, stop, step) to control your loop.
Example:
Output:
You can even skip numbers by adding a step:
Output:
Step 3 – Looping Through a List
Lists are collections of values.
You can loop through each element directly.
Example:
Output:
You can also loop by index using range(len(list)):
Step 4 – Looping Through a String
Strings are sequences too! You can loop through each character.
Example:
Output:
Step 5 – Using For Loops with Logic
You can combine loops with if statements to make your code smarter.
This example prints only even numbers:
Step 6 – Mini Challenge
Challenge: Print all the letters in your name, one by one, in uppercase.
Example output:
Try extending it, make it show both lowercase and uppercase letters side by side!
You can download the challenge code from my GitHub here and run it yourself.
You can download the bonus challenge code from my GitHub here and run it yourself.
Step 7 – Key Takeaways
forloops repeat actions for every item in a sequencerange()generates numbers automatically- You can loop through lists, strings, and even custom sequences
- Combine loops and logic to control how and when actions happen
Next up — Day 9: While Loops
You’ll learn how to make loops that run until something changes.All example files for this series are available on my GitHub: Learn-Python-in-30-Days
You can see the full series here Learn Python in 30 Days series!
Hope you have enjoyed this post, thanks Matty







Comments
Post a Comment