Loops in Python

Looping means repeating something over and over until a particular condition is satisfied. Here we will learn about following topics under loops in python:

  • While Loops
    • Sum 1 to 10
    • Adding number
  • Infinite Loops
  • For Loops
    • Sum 1 to 10
  • Break and Continue Keyword
    • Break
    • Continue
  • Step argument
  • For loop and string

While Loops

With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i <= 10:
    print("hello anisha")
    i=i+1
hello anisha
hello anisha
hello anisha
hello anisha
hello anisha
hello anisha
hello anisha
hello anisha
hello anisha
hello anisha
  • Sum 1 to 10
    In this program we will sum number from 1 to 10 using while loop.
total = 0
i = 1
while i <= 10:
    total = total + i 
    i = i + 1
    print(total)
1
3
6
10
15
21
28
36
45
55
  • Adding number
    In this program we will add a number
num = input("enter a number ")
total = 0
i = 0
while i < len(num):
    total = total + int(num[i])
    i = i+1
print(total)
enter a number 12345
15

Infinite Loops

A continuous repetitive conditional loop known as a "infinite loop" in Python continues to run until an outside factor intervenes in the execution flow, such as a lack of CPU memory, a failed feature or error code that terminated the execution, or a new feature in one of the legacy systems that requires code integration.

i = 0
while i <= 10:
    print("error")
# to stop the infinite loops we have to press ctrl + c

For Loops

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

for i in range (10):
    print("hello")
    
  • Sum 1 to 10
    In this program we will sum number from 1 to 10 using for loop.
total = 0
for i in range(1,11):
    total = total + i
print(total)

Break and Continue Keyword

The Python break statement stops the loop in which the statement is placed. A Python continue statement skips a single iteration in a loop. Both break and continue statements can be used in a for or a while loop.

  • Break
for i in range (1,11):
    if i == 5:
        break
    print(i)
  • Continue
for i in range (1,11):
    if i == 5:
        continue
    print(i)

Step argument

Step argument in python refers to jumping of certain step during exectuionof program.

for i in range(1,11,2):
    print(i)
1
3
5
7
9

For loop and string

name = " anisha"
for i in range(len(name)):
    print(name[i])
 
a
n
i
s
h
a