Loops in Python

Amit Dhanwani on September 6, 2022


What are Loops in Python?

Coding is a basic literacy in the digital age, and kids need to understand and work with the technology around them. Having children learn coding at a young age prepares them for the future.

Coding helps children with communication, creativity, math, writing, and confidence. Coding is proven to improve logical reasoning and problem-solving skills.

Children can grow their math skills while coding, without even realizing it. Coding improves Logical thinking, the act of analyzing a situation and coming up with a reasonable solution is known as logical thinking, and Coding is the same, where you create something from scratch, whereas while writing the first logic you think of the next 10 steps.

Loops are a powerful abstraction in Python. Iterative looping, which loops employ, helps us eliminate repetitive code. The main objective of this article is to help you iterate through a series of elements using various for-loop versions and while loops.

Introduction:

Many new employment possibilities have emerged for youngsters that learn Python programming, as Python is being used in many sophisticated disciplines.

Learning Python today will enable kids to develop life skills. This will not only improve their skills but also it would strengthen their academic performance.

Loops

Loops are a formidable abstraction in Python. Iterative looping, which loops employ, helps us eliminate repetitive code. This is incredibly useful when you want to repeat a function numerous times.

Simply write the initial code, and then repeat the function until a predetermined condition is not achieved. Loops are used to repeatedly execute the same or similar code.

This number of times may be limited to a certain number or might be determined by the fulfillment of a particular condition.

 

For Loop

The for loop’s functionality is not significantly different from all of those of many other programming languages.

This blog focuses in extensive detail on the Python for loop and teaches you how and where to iterate over a variety of sequences, such as lists, tuples, and more.

  1. Basic syntax of For Loop:
    The basic syntax of for loop in python is as follows:
for iterator_variable in sequence_name:
Execution Statements
---
Execution Statement

Table 1: Description of for loops parameters.

Sr. NoParameterExplanation 
1forThe statement’s first word begins with the word “for,” which denotes the start of the for a loop.
2iterator variableThe iterator variable follows, iterating through the sequence and allowing for a variety of operations to be carried out within the loop.
3InPython’s “in” keyword instructs the iterator variable to loop over the sequence’s elements.
4sequenceThe sequence parameter, which may be a list, a tuple, or any other type of iterator, is the last.
5Execution statementsYou can explore with the iterator variable and execute different functions in the loop’s Execution statements section.
  • 2. Flowchart of for loop
  • Examples:Using for loop to print each letter in a string individually
codingal = "kids fall in love with coding"

for i in codingal:

    print(i)

k
i
d
s

f
a
l
l

i
n

l
o
v
e

w
i
t
h

c
o
d
i
n
g

Instead of considering the string as a whole, Python views a “string” as a sequence of characters.

Iterating through a Python list or tuple with the for loop

codingal = ["kids", "fall", "in", "love", "with", "coding"]

for i in codingal:

   print(i)

kids
fall
in
love
with
coding

Iterable objects include lists and tuples.

Python for loops nested

Nested for loops are for loops inside other for loops. The words will be repeated in the first loop (parent loop) one at a time. The characters of each word will be looped over in the second loop (child loop).

codingal = ["kids", "fall", "in", "love", "with", "coding"]

for i in codingal:

  print("Each letter in the following lines will be printed:" +i)

  

  for j in i:

    print(j)

  print("")

Each letter in the following lines will be printed:kids
k
i
d
s

Each letter in the following lines will be printed:fall
f
a
l
l

Each letter in the following lines will be printed:in
i
n

Each letter in the following lines will be printed:love
l
o
v
e

Each letter in the following lines will be printed:with
w
i
t
h

Each letter in the following lines will be printed:coding
c
o
d
i
n
g


Python for loop using the method
range() :

Range() is a built-in function in Python. The range function works incredibly well when you need to provide a range of items to print out or how many times the for loop should execute.

for i in range(9):

  print(i)

0
1
2
3
4
5
6
7
8

In addition to the start and stop parameters, the range function likewise contains another. The step parameter is this. It specifies how many integers should be skipped by the range function between each count.

for i in range(1,9,2):

  print(i)

1
3
5
7

For loop with a break statement:

To quit the for loop before it has finished, use the break statement. It is implemented to end the for loop when a particular condition is satisfied.

codingal = [1, 2, 3, 4, 5]
i=5
present=False
for j in codingal:
 if j == i:
 found = True
 break
print(f"The number {i} is present in the codingal list.")

The number 5 is present in the codingal list.


For loop with a
continue statement

When a certain condition is met, the for loop body can be bypassed using continue statements inside the for loop.

codingal = [1,-2, -3, 4, 5]

i=0

for j in codingal:

  if j<0:

    continue

  i += j

print(f"sum of positive number is {i}.")

sum of positive number is 10.


For loop with the
else block:

With a Python for loop, we may employ an else block. Only when a break statement does not terminate the for loop is the else block executed.

student_name = "Penguin"

percentage = {"Penguin": 99, "Hat": 25, "Champ": 37}

for i in percentage:

     if i == student_name:

         print(percentage[i])

         break

else:

     print("No such student found in the database.")

99

Python program to find out the average of a set of integers

count = int(input("Enter the count of numbers: "))
i = 0
sum = 0
for i in range(count):
   x = int(input("Enter an integer: "))
   sum = sum + x
avg = sum/count
print(" The average is: ", avg)

Enter the count of numbers: 10
Enter an integer: 2
Enter an integer: 5
Enter an integer: 6
Enter an integer: 4
Enter an integer: 8
Enter an integer: 9
Enter an integer: 7
Enter an integer: 5
Enter an integer: 0
Enter an integer: 3
The average is: 4.9


While Loop

While loops are used in Python to continually run a block of statements until a specified condition is met.

And the line in the program that follows the loop is run when the condition switches to false. 

  1.       Basic syntax of While Loop

    while expression:
    
             Body/execution statements of while loop

    Table 2: Description of while loop parameters.

    Sr. No.ParametersExplanation
    1ExpressionThe test expression is tested first in the while loop. Only in the event that the expression returns True are the body/execution statements of the loop executed. The expression is tested once again after the first repetition. Until the test expression evaluates to False, this procedure keeps going.
    2IndentationIn Python, indentation is used to identify the while loop’s body. The first line that isn’t indented after the indentation signals the end of the body.
    3InterpretationPython understands any value other than zero as True. False is the interpretation of None and 0 in python.

     

  2. Flowchart of while loop
  3. Examples:

Simple While Loop

codingal = 0

while (codingal < 9):

    codingal = codingal + 1

    print("Lets make kid fall in love with coding")

Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding

While loop to determine the number of digits of an integer n

n = int(input("Enter the number:"))
length = 0
while n > 0:
n //= 10
length += 1
print("length of the number is:", length)

Enter the number:999
length of the number is: 3

Combining while loops with the else statement:

Only when your while condition becomes false does your else statement come into play. It won’t be run if you exit the loop or if an exception is thrown.

Example 1:

codingal = 0

while (codingal < 9):

    codingal = codingal + 1

    print("Lets make kid fall in love with coding")

else:

           print("Codingal is on the misson to make every kid fall in love with coding")

Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Lets make kid fall in love with coding
Codingal is on the misson to make every kid fall in love with coding

Example 2:

for i in range(5):
a = int(input("Enter the number:"))
if a < 0:
print('Met a negative number', a)
break
else:
print('No negative numbers met')

Output 1:
Enter the number:2
Enter the number:5
Enter the number:6
Enter the number:9
Enter the number:8
No negative numbers met

Output 2:
Enter the number:2
Enter the number:5
Enter the number:6
Enter the number:9
Enter the number:8
No negative numbers met

While loops with the continue statement

Continue is another another command that controls how the loop is executed. If the Python interpreter encounters continue while iterating the loop, it skips all remaining instructions and moves on to the subsequent iteration.

 

for num in range(2, 10):
     if num % 2 == 0:
       print("Found an even number", num)
       continue
    print("Found a number", num)

Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

If the break and continue statements are included within many nested loops, only the innermost loop will be affected by their presence.

for i in range(4):
    for j in range(6):
       if j > i:
break
print(i, j)

0 0
1 0
1 1
2 0
2 1
2 2
3 0
3 1
3 2
3 3

While loops with the if-elif-else statement

codingal = 0

while codingal < 3:
     if codingal == 0:
         print("codingal is",codingal)
         codingal += 1
    elif codingal == 1:
         print("codingal is",codingal)
         codingal += 1
    else:
        print("codingal is",codingal)
        codingal += 1

codingal is 0
codingal is 1
codingal is 2

While loop for printing all letters except some letters:

i = 0
coding = "Codingal is on the misson to make every kid fall in love with coding"

while i < len(coding):
  if coding[i] == "e" or coding[i] =="o":
    i += 1
    continue

  print("Final letter",coding[i])
  i += 1

Final letter C
Final letter d
Final letter i
Final letter n
Final letter g
Final letter a
Final letter l
Final letter
Final letter i
Final letter s
Final letter
Final letter n
Final letter
Final letter t
Final letter h
Final letter
Final letter m
Final letter i
Final letter s
Final letter s
Final letter n
Final letter
Final letter t
Final letter
Final letter m
Final letter a
Final letter k
Final letter
Final letter v
Final letter r
Final letter y
Final letter
Final letter k
Final letter i
Final letter d
Final letter
Final letter f
Final letter a
Final letter l
Final letter l
Final letter
Final letter i
Final letter n
Final letter
Final letter l
Final letter v
Final letter
Final letter w
Final letter i
Final letter t
Final letter h
Final letter
Final letter c
Final letter d
Final letter i
Final letter n
Final letter g

Conclusion

Python’s for loop is reasonably comparable to that in other programming languages. We may control the execution with the for loop by using the break and continue statements. 

And while loop test the expression (condition) is true or not, a while loop in Python is used to cycle across a block of code if the condition is true. When uncertain how often to iterate, we often implement a while loop. In Python, however, the for loop and while loop can incorporate an optional else block.

The rules of Python syntax are simple enough for anyone to learn. Hence it’s a perfect first programming language to learn. While Python can be used for simple tasks, academics, data journalists, researchers, and millions of working programmers make a living writing Python every day.

Codingal offers Python for kids course to help your child enhance cognitive, logical, and computational skills. We provide 1:1 live interactive online coding classes with expert coding instructors for kids. Along with lifetime access to course content and downloadable learning resources, to cater to every child’s need by providing a personalized journey. Try a free class today!

 

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class