for loop with exercises and examples

by Sam  


For loop in python is different from other programming languages like c, c++ and java. I noticed that for loop in python is similar with foreach in PHP .

This page will show you how to use For Loop using Python 3.

Examples

1. Print all values


# Output: 1234567
numbers = [1, 2, 3, 4, 5, 6, 7]
for num in numbers:
print(num)

2. Use of Range in for loop

Let’s range the output to be displayed. Below, I added end="" in order to print it inline with the other numbers.


# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x, end="")

If you want to set the range of two arguments.


# Output: 345
for x in range(3, 6):
print(x , end="")

Using three arguments, you can set the range while automatically skip the iteration depending on the steps. From the example below, we’ll start at 2 and end at 10. The value of x will be printed only every after 3 steps. So, the output is 2 5 8.


# Output: 258
for x in range(2, 10, 3):
print(x , end="")

3. Use of Continue

Continue is used to skip the current block, and return to the main loop. From example below, if x is equal to 4, it won’t read the next line, it goes back to for loop and iterate again.


#output: 1235
for x in range(1, 6):
if x == 4:
continue
print(x , end="")

4. Use of break

Just like with continue, break won’t read the next line. But, the difference is that, break doesn’t go back to the main loop. Examine the xample below.


#output: 123
for x in range(1, 6):
if x == 4:
break
print(x , end="")

Exercises

Consider the numbers variable as your input.

numbers = [234,235,236,237,238,239,240]

Exer 1. Create a program that will display the values above except 238.
Exer 2. Display odd integers only.
Exer 3. Display the First and End values only.

Try the exercises above and comment your solution below.



Leave a Reply

Your email address will not be published. Required fields are marked *


Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote