Python Loops
Python Loops
• Python programming language provides the following types of loops to handle looping
requirements.
• Python provides three ways for executing the loops.
• While all the ways provide similar basic functionality, they differ in their syntax and
condition-checking time.
• Loops are a fundamental concept in programming and are used to repeat a block of code
multiple times.
• In Python, there are two main types of loops: for loops and while loops.
While loop
• In python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied.
• And when the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax
while condition:
## do something
count = count + 1
• All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code.
• The loop body will execute repeatedly as long as the condition is true.
i=1
while i<5:
i=i+1
print('Inside while loop')
print('This is outside while loop')
# 'Inside while loop' will be printed until i>=5
x=1
print('Number\t'+'Square')
while x<=10:
print(x,'\t',x**2)
x=x+1
print('Done')
Number Square
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
Done
# In this example, the program prompts the user to enter their age
using the input() function, which returns a string.
# The string is then converted to an integer using the int() function.
# The loop body checks if the user's age is outside the valid range of
0 to 120.
# If the age is invalid, the program prints an error message and
prompts the user to enter their age again.
# Once a valid age is entered, the loop terminates and the user's age
is printed.
• (ii) If the test expression is False, the while loop is not entered at all and the
program move to the next line of code after the while loop.
• (iii) However, if the test expression evaluates to True, then the while loop is entered
and one iteration of the entire while loop is executed. After completion of one
iteration, the expression of while loop is again tested. If the test expresion evaluates
to False, then the while loop is not entered again. However, if the while loop test
expression again evaluates to True, then the while loop is executed again. This
process goes on until the test expression of the 'while' loop evaluates to False.
• (iv) If the while boolean expression does not evaluate to False ever, then you will get
an infinite loop, that is, a loop from which the script cannot exist.
• (v) If initialy the boolean expression of the while loop evaluates to False, then the
while loop is not run even once.
---> You can combine a while with an 'else' statement also
---> As long as Boolean test condition of the 'while loop'
evaluates to True, the 'while loop' is executed.
---> However, when the boolean expression of the 'while loop'
evaluates to False, then the 'else' block is executed
# Syntax of while loop with the optional else is as follow
# while test_condition: # Loop test_condition must eval to bool
True or False
# statements # Loop Body if test_condition is True
# else: # Optional else
# statements # executed if test_condition is False
i=0
while i<10:
print('Inside while')
i=i+1 # you can write increment as i+=1
else:
print("Inside else i.e. outside while ")
Inside while
Inside while
Inside while
Inside while
Inside while
Inside while
Inside while
Inside while
Inside while
Inside while
Inside else i.e. outside while
import random
Enter number99
Guess lower
Enter number98
Guess lower
Enter number97
Guess lower
Enter number96
Guess lower
Enter number90
Guess lower
Enter number80
Guess lower
Enter number70
Guess lower
Enter number60
Guess lower
Enter number50
Guess Higher
Enter number55
Guess Higher
Enter number56
Guess Higher
Enter number58
Guess lower
Enter number57
Correct Answer
You took 13 attempt
Break
syntax-->> break
• In Python, break is a keyword used inside loops to terminate the loop prematurely.
• When the break statement is executed inside a loop, the loop is immediately exited
and the program continues to execute the code after the loop.
• Thus, break is a useful tool for controlling the flow of loops in Python, and can help
to improve the efficiency and effectiveness of your code.
i = 0
while i < 10:
if i == 6:
break # here when i==6 is True, immidiately programm will
stop to execute and we are outside while loop
print(i)
i += 1
0
1
2
3
4
5
Continue statement in Python
In Python, continue is a keyword used inside loops to skip the current
iteration and move on to the next iteration of the loop.
When the continue statement is executed inside a loop, the current
iteration is immediately terminated, and the program jumps to the
beginning of the next iteration.
So, with the continue statement, the loop does not terminate, only the
remaining statements are skipped.
i=0
while i<10:
if i%2==0:
# continue
print(i)
i=i+1
# This program will go in infinite loop because of continue statement
{as condition is true the the code go to next line and will execute
infinitely}
File "C:\Users\MDSPPU\AppData\Local\Temp\
ipykernel_11000\2166683932.py", line 5
print(i)
^
IndentationError: expected an indented block
i = 0
while i < 10:
i += 1
if i % 2 != 0:
continue
print(i)
2
4
6
8
10
i=0
while i<10:
i+=1
if i==6:
continue
print(i)
1
2
3
4
5
7
8
9
10
Enter a number: 56
Not a Prime number
import math
Enter a number: 89
89 is a prime number.
Syntax
for value in sequence:
#execute code here
# Example
for i in "Hello":
print(i,end=" ")
H e l l o
if num < 2:
is_prime = False
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Enter a number: 5
Factorial of 5 is 120
[11]
[11, 12]
[11, 12, 13]
[11, 12, 13, 14]
[11, 12, 13, 14, 15]
[11, 12, 13, 14, 15, 16]
[11, 12, 13, 14, 15, 16, 17]
[11, 12, 13, 14, 15, 16, 17]
divisor_sum = 0
for i in range(1, num):
if num % i == 0:
divisor_sum += i
if divisor_sum == num:
print(num, "is a perfect number.")
else:
print(num, "is not a perfect number.")
Enter a number: 28
28 is a perfect number.