For loops are one of the basic iterative structures available in most programming languages. You’ll also find that there is a variant of typical for loops called foreach loops that lets you access elements of a sequence. In python 3, the for loop works similarly to the foreach loop.
Python 3 For Loop Syntax
From the above image, you can see the syntax of for loops. Python 3 for loop syntax resembles pseudo code, which makes it easier to understand and read python code. Python has avoided providing a standard integer increment based for loops and provided a single for loop variant that works similarly to a typical foreach loop. The reason behind this is to avoid having multiple ways to do the same thing, therefore making code more understandable.
This code will print a, b, c in 3 separate lines.
Reversing a List Using Python 3 For Loop
Now let’s attempt to reverse a string using a for loop. String is a sequence of characters.
According to python docs:
Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.
Note: There are better ways to reverse a string. This is a simple use of Python 3 for loop.
Range class allows you to create a simple object that represent a sequence of numbers calculated from provided instructions.
Let’s see how it works:
Explanation of Range Class
Range allows you to name the start, stop and step of a sequence. (Negative, positive and zero can be used, you can try and experiment with this). Range class excludes stop value from the calculated sequence.
You can just specify ‘Stop‘ value. This is the typical use case for ‘range‘ class.
For Loop Continue Statement
You can skip the loop to next element of sequence using ‘continue‘ statement.
Imagine that you want to find the numbers that are lower than 10 but also not divisible by 4. I have captured executing this in the GIF above.
Here is the explanation:
In this scenario, I’m using modulus operator to see if the number is divisible.
Break and Else Statement
You know that the ‘continue‘ statement allows skipping to occur. What does ‘break‘ do ? It allows the program to exit from the loop.
Now let’s see the explanation.
You can use the ‘else‘ statement to do something if ‘break‘ did not occur.
Exercise 01: Printing Numbers
- Print numbers of a given range.
- Avoid printing numbers that are divisible by 4.
- Do not print numbers larger than or equal to 11.
- If you encounter a number larger than or equal to 11 Print “I’m tired of counting”.
- If you’re still doing this, print “I didn’t give up”.
for i in range(15): if i % 4 == 0: continue if i >= 11: print("I'm tired of counting.") break print(i) else: print("I didn't give up")
Like what you see? Subscribe to our email list and hit us with a like on our Facebook page to get the latest news updates and tutorials straight to your newsfeed!