Introduction
“We do what we are and we are what we do”
In this article, we will discuss for loops and the implementation of for loops with respect to integers and strings.
For loop
For loop is also called a finite loop. We use for loop whenever we know how many times the loop should be executed. A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Since we are aware of only integers and strings we can see in detail how to implement for loop in those data types.
Moving further when we learn in detail regarding the data types we can also learn the implementation of for loop then and there.
Syntax
for i in <itereable>:
Statements
Here, i represents iterable, we can use any valid variable name in place of i which will hold a single value at a time from the <iterable>. Statements are to be indented which represents that these are statement blocks that should be executed inside for loop.
Flow chart
For loop with numbers
For loop can be written with respect to numbers as if we know the number of times a loop should be executed.
To make this easy we have a built-in function to implement for loop in an easy manner. First, let us look at the build-in function then we can discuss implementing them in the for a loop.
range()
The range function is used to generate a range of numbers. For example, range(10) will provide you with numbers from 0 to 9.
Syntax
range (start value, end value, steps)
Here,
A start argument is a starting number of the sequence. By default, it starts with 0 if not specified.
A stop argument is an upper limit that is, generating numbers up to this number. The range() doesn’t include this number in the result.
The step is the increment number. The default value of the step is 1 if not specified.
Example
print(list(range(10)))
print(list(range(2,8)))
print(list(range(2,10,2)))
print(list(range(10,0,-2)))
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 4, 6, 8]
[10, 8, 6, 4, 2]
Implementation of range in the loop
We can write the range function in place of iterable so that i will loop through the value of the range function.
Syntax:
For i in range(<start>,<end>,<step>):
Statements
Examples
#Program to print first 10 numbers
for i in range(10):
print(i,end=" ")
print("\nthank you")
0 1 2 3 4 5 6 7 8 9
thank you
#program to print first 10 even numbers
for i in range(0,20,2):
print(i, end=" ")
print("\nthank you")
0 2 4 6 8 10 12 14 16 18
thank you
#program to print sum of first 10 numbers
sum=0
for i in range(1,11):
sum=sum+i
print("Sum of first 10 numbers is ",sum)
Sum of first 10 numbers is 55
"""
*
* * *
* * * * *
print the above pattern"""
for j in range(1,6,2):
print("* "*j)
For loop with strings
For loop can be used to traverse through every character in a string.
example
for i in "hello":
print(i)
h
e
l
l
o
In the code snippet, we are parsing a string hello inside the loop, so c takes each and every character and prints them separately. Since a print statement creates a new line every character is printed in separate lines.
Break, continue, and else clause
They work as same as they worked in the while loop.
Break- Break statement breaks the entire loop and continues to execute the statements after a loop.
Continue- Continue statement breaks the current iteration and continues the loop by checking the next condition.
Else clause- else clause is executed when the loop completes its execution without any break in between.
To know in detail about these, click on While loop in python.
Nested loops
As the name suggests python allows the creation of many loops inside loops. We can write a while loop inside for loop and a for loop inside a while loop.
We can also have conditional branching at any point of the program.
Do remember, the break and continue statement does its operation only to its nearest loop, not on all the loops.
Example
#write a program to help your teacher find the total and average of 5 for every student in the class.
do_you=""
while do_you!="exit":
total=0
for i in range(1,6):
mark=int(input("Enter your mark: "))
total=total+mark
avg=total/5
print("Total- ",total,"\nAverage- ",avg)
do_you=input("Press enter to calculate for another student\nType exit to exit\n")
print("Thanks for using the calculator")
Practice yourself
- Print first 10 odd numbers.
- Display multiplication table of user’s choice.
- Show the product of the first 100 numbers.
- Find the length of the word the user entered including spaces.
- Write a program to check if the user typed a palindrome.
- Pattern printing
*
* * *
* * * * * *
* * *
*
Conclusion
I hope, this article gives an idea of implementing for loop in python.
Thus we have covered the two basic types of looping in Python. Practice getting familiar with the topics.
“The best way to learn is by doing”
Pingback: Rock Paper Scissor Game -