Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Python Loops

Uploaded by

rohitdc17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Loops

Uploaded by

rohitdc17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

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

Python program to illustrate


while loop
counter variable

while (condition on counter variable):

count = count + 1

Statement which you want to execute inside a while loop


Flowchart of While loop

• 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.

• Python uses indentation as its method of grouping statements.


• The condition is a boolean expression that determines whether the loop should
continue or not.

• 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

Inside while loop


Inside while loop
Inside while loop
Inside while loop
This is outside while loop

# Examples of while loop


# Write a Python programme which will return the square of numbers
from 1 to 10 using while loop

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

# example demonstrates how to use a while loop to validate user input:


age = int(input("Please enter your age: "))
while age < 0 or age > 120:
print("Invalid age. Please enter a valid age between 0 and 120.")
age = int(input("Please enter your age: "))
print("Your age is:", age)

# 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.

Please enter your age: 10


Your age is: 10

# Programme to calculate First n terms of Fibonacci Sequence


num = int(input("Enter the number of Fibonacci sequence terms to
generate: "))
a, b = 0, 1
i = 0
while i < num:
print(a, end=" ")
a, b = b, a + b
i=i+1

Enter the number of Fibonacci sequence terms to generate: 12


0 1 1 2 3 5 8 13 21 34 55 89

The while loop work as follow:


• (i) At first the boolean test expression is checked.

• (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

Infinite While Loop in Python


• If we want a block of code to execute infinite number of time, we can use the while loop
in Python to do so.
i=0
while i<1:
print('This is infinite loop')
i=i+1 # if you reomve the increment in i here then loop will
execute infinitely

This is infinite loop


# Write a programme which will print multiplication table for a number
using while loop
num=int(input("Enter number here: "))
i=1
while i<=10:
print(num,"*",i,"=",num*i)
i=i+1

Enter number here: 12


12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120

import random

# Guessing Game by using While loop


num=random.randint(1,100)
guess_num=int(input("Enter number"))
i=1
while guess_num != num:
if guess_num>num:
print('Guess lower')
else:
print("Guess Higher")
guess_num=int(input("Enter number"))
i=i+1
print("Correct Answer")
print("You took",i,'attempt')

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 , Continue, pass in Loops

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.

• break statements are used inside loops or nested 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.

# While loop with break statement

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

while True in Python


• In Python, while True is a construct that creates an infinite loop that will continue
indefinitely until it is explicitly broken using a break statement.
• This construct is often used when you need to repeatedly execute a block of code without
knowing in advance how many times the loop will need to run.
while True:
pswd = input("Enter your passwor here: ")
if pswd == "ABC@123":
print("Yehhh, you entered correct password")
break

print('You provide wrong password')

# In this example, the loop will continue to execute indefinitely


until the user types "ABC@123" as their password,
# at which point the break statement is executed and the loop is
terminated.

Enter your passwor here: 54665


You provide wrong password
Enter your passwor here: ABC@123
Yehhh, you entered correct password
It's important to be careful when using while True, as an infinite loop
can consume a lot of system resources and cause your program to
become unresponsive or crash.
To avoid this, you should always ensure that there is a way to break
out of the loop, either by using a conditional statement that will
eventually evaluate to false, or by including a break statement inside
the loop that will terminate the loop under certain conditions.

# Python Programme to check wheather given integer is prime or not ?


num = int(input("Enter a number: "))

# 1 is not a prime number


if num == 1:
print("1 is not a prime number.")
else:
i = 2
while i < num:
if num % i == 0:
print("Not a Prime number")
break
i += 1
else:
print(num, "is a prime number.")

Enter a number: 56
Not a Prime number

# Python program to force user to enter correct or you can say


perticular type of input
# in this case we will force to user to enter a valid age which is
integer only
while True:
myAge=input("Give your age in yeras-->> ")
if myAge.isdigit():
print("You are", myAge, 'years old')
break
print("You did not give valid credential")
#### While True create infinite loop

Give your age in yeras-->> 98.998


You did not give valid credential
Give your age in yeras-->> 2133lk
You did not give valid credential
Give your age in yeras-->> jkjj
You did not give valid credential
Give your age in yeras-->> jjjh
You did not give valid credential
Give your age in yeras-->> jjhhbb
You did not give valid credential
Give your age in yeras-->> jh
You did not give valid credential
Give your age in yeras-->> 25
You are 25 years old

# Python programme to check given integer is prime or not

import math

num = int(input("Enter a number: "))

# 1 is not a prime number


if num == 1:
print("1 is not a prime number.")
else:
# check for factors up to the square root of num
sqrt_num = int(math.sqrt(num)) + 1
for i in range(2, sqrt_num):
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")

Enter a number: 89
89 is a prime number.

For loop in Python


for loop is a definite loop whereas 'while' loop is indefinite loop.
• A 'while' loop is an indefinite loop because it simply loops till a condition becomes False.
• A 'for' loop , on other hand, runs as many times as there are items in a set
• In Python, the for loop is used to iterate over a sequence of values, such as a list, tuple, or
string.
• It allows you to execute a block of code for each value in the sequence.

Syntax
for value in sequence:
#execute code here

# Example
for i in "Hello":
print(i,end=" ")

H e l l o

# Program to determine wheather number is prime or not using for loop


num = int(input("Enter a number: "))
# _prime = True

if num < 2:
is_prime = False

for i in range(2, num):


if num % i == 0:
is_prime = False
break

if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Enter a number: 888


888 is not a prime number

# Taking input from user


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Finding the GCD of the two numbers


gcd = 1
for i in range(1, min(num1, num2) + 1):
if(num1 % i == 0 and num2 % i == 0):
gcd = i

# Finding the LCM of the two numbers


lcm = max(num1, num2)
while(True):
if(lcm % num1 == 0 and lcm % num2 == 0):
break
lcm += 1

# Printing the GCD and LCM of the two numbers


print("GCD of", num1,"and", num2,"is", gcd)
print("LCM of", num1,"and", num2,"is", lcm)

Enter first number: 20


Enter second number: 22
GCD of 20 and 22 is 2
LCM of 20 and 22 is 220

# Programme for factorial


num = int(input("Enter a number: "))
fact = 1
for i in range(1, num + 1):
fact = fact * i
print("Factorial of", num, "is", fact)

Enter a number: 5
Factorial of 5 is 120

# Program to remove duplicates items from a list


# input--->>> L=[11,12,11,12,13,14,15,16,17]
# output--->>> L=[11,12,13,14,15,16,17]
L=[11,12,11,12,13,14,15,16,17]
M=[]
for i in L:
if i not in M:
# print(M)
M.append(i)
print(M)
print(M)

[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]

# A perfect number is a positive integer that is equal to the sum of


its proper divisors (excluding itself).
# Example 28=1+2+4+7+14
num = int(input("Enter a number: "))

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.

You might also like