0% found this document useful (0 votes)
50 views11 pages

If Classnote

Uploaded by

vrjs27 v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views11 pages

If Classnote

Uploaded by

vrjs27 v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

a =10

b=20
if a is b :
print (" both are equal")
else :
print (" not same")
if id(a) == id(b):
print (" both are equal")
else :
print (" not same")

x = 20
y = 20
if x is not y:
print (" x is not y ")
else :
print (" same")
==========================
# find the leaf bytearray
# 2024
num =2024
if num%4==0:
print ("leaf year")
else :
print (" not leaf ")
==========================
num=int(input("Enter a number:"))
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome!")
else:
print("Not a palindrome!")
===========================================
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")
==================================================
while loop with pass keyword
The "pass" keyword does nothing. It can be used as a placeholder for the code or
block of code that has to be implemented in the future.

mystr = "codescracker"
count = 0

while count < len(mystr):


count = count+1
pass

print("Length of String =", count)

# in operator
a = 10
b = 20
list =[ 2,4,5,6,10,21,30]
if a in list:
print("a is availale")
else :
print("not available ")
# not in operator
if b not in list :
print(" b not in list")
else :
print(" available ")
=================
why we are useing loops
loops are use for specific block of code repeatly calling

use : reusebility of code


decreaseing numer of lines
improving performance
useing loop we can traverse over the elements of data
[ 60]
= [1],[2]

controlling : break, continue, pass


==========================================
#statement
#while condition:
#statement

# print 10 numbers
i = 1
while i < 10:
print(i)
i= i + 1
======================

mystr = "helloworld"
count = 0

while count < len(mystr):


count = count+1
pass

print("Length of String =", count)

===============================
num = [34, 12, 54, 23, 75, 34, 11]

def prime_number(number):
condition = 0
iteration = 2
while iteration <= number / 2:
if number % iteration == 0:
condition = 1
break
iteration = iteration + 1

if condition == 0:
print(f"{number} is a PRIME number")
else:
print(f"{number} is not a PRIME number")
for i in num:
prime_number(i)
==================================
Home » Python » Python while loop
Python while loop
Updated on: June 25, 2021 | 3 Comments

In this article, you will learn what is while loop in Python? and how to write it.
We use a while loop when we want to repeat a code block.

Also, Solve:

Python loop Exercise


Python loop Quiz
Table of contents
What is a while loop in Python?
Syntax for while loop
Example of while loop in Python
Flowchart of while loop
Why and When to Use while Loop in Python
If-else in while loop
Transfer statements in while loop
Break Statement
Continue Statement
Pass Statement
Nested while loops
for loop inside a while loop
Else statement in while loop
Reverse while loop
Iterate String using while loop
Iterate a List using while loop
Next Steps
What is a while loop in Python?

In Python, The while loop statement repeatedly executes a code block while a
particular condition is true.

count = 1
# condition: Run loop till count is less than 3
while count < 3:
print(count)
count = count + 1
Run
In simple words, The while loop enables the Python program to repeat a set of
operations while a particular condition is true. When the condition becomes false,
execution comes out of the loop immediately, and the first statement after the
while loop is executed.

A while loop is a part of a control flow statement which helps you to understand
the basics of Python.

We use a while loop when the number of iteration is not known beforehand. For
example, if you want to ask a user to guess your luck number between 1 and 10, we
don’t know how many attempts the user may need to guess the correct number. In such
cases, use a while loop.
Indefinite Iteration: An unknown number of iterations. Ask the user to guess the
lucky number. You don’t know how many attempts the user will need to guess
correctly. It can be 1, 20, or maybe indefinite. In such cases, use a while loop.
Finite Iterations: Fixed number of iterations. Print the multiplication table of 2.
In this case, you know how many iterations you need. Here you need 10 iterations.
In such a case use for loop.

So, when number of iteration is not fixed always use the while loop.

while loop in Python


while loop in Python

Syntax for while loop


while condition:
# Block of statement(s)
The while statement checks the condition. The condition must return a boolean
value. Either True or False.
Next, If the condition evaluates to true, the while statement executes the
statements present inside its block.
The while statement continues checking the condition in each iteration and keeps
executing its block until the condition becomes false.

Example of while loop in Python


Let’s see the simple example to understand the while loop in Python

Example: Print numbers less than 5

In the above example, the while loop executes the body as long as the counter
variable is less than 5. In each iteration, we are incrementing the counter by 1.
Eventually, the counter variable will no longer be less than 5, and the while loop
will stop executing.

count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1
Run
Output:

1
2
3
4
Note: The loop with continuing forever if you forgot to increment counter in the
above example

Example 2: Check how many times a given number can be divided by 3 before it is
less than or equal to 10.

In this example, the total iteration will vary depending on the number. when a
number of iteration is not fixed always use the while loop.

count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)
Run
Output:

Total iteration required 3

Flowchart of while loop


while loop flowchart
while loop flowchart

Why and When to Use while Loop in Python


Now, the question might arise: when do we use a while loop, and why do we use it.

Automate and repeat tasks.: As we know, while loops execute blocks of code over and
over again until the condition is met it allows us to automate and repeat tasks in
an efficient manner.
Indefinite Iteration: The while loop will run as often as necessary to complete a
particular task. When the user doesn’t know the number of iterations before
execution, while loop is used instead of a for loop
Reduce complexity: while loop is easy to write. using the loop, we don’t need to
write the statements again and again. Instead, we can write statements we wanted to
execute again and again inside the body of the loop thus, reducing the complexity
of the code
Infinite loop: If the code inside the while loop doesn’t modify the variables being
tested in the loop condition, the loop will run forever.
Let’s test the above statements.

Example 1: Assure proper input from user

In this example, we want a user to enter any number between 100 and 500. We will
keep asking the user to enter a correct input until he/she enters the number within
a given range.

number = int(input('Enter any number between 100 and 500 '))


# number greater than 100 and less than 500
while number < 100 or number > 500:
print('Incorrect number, Please enter correct number:')
number = int(input('Enter a Number between 100 and 500 '))
else:
print("Given Number is correct", number)
Run

Output:

Enter any number between 100 and 500 700


Incorrect number, Please enter correct number:
Enter a Number between 100 and 500 98
Incorrect number, Please enter correct number:
Enter a Number between 100 and 500 300
Given Number is correct 300
Example 2: Infinite while loop

# Infinite while loop


while True:
print('Hello')
If-else in while loop
In Python, condition statements act depending on whether a given condition is true
or false. You can execute different blocks of codes depending on the outcome of a
condition. If-else statements always evaluate to either True or False.

We use the if-else statement in the loop when conditional iteration is needed.
i.e., If the condition is True, then the statements inside the if block will
execute othwerwise, the else block will execute.

Syntax of if-else statement

if condition :
block of statements
else :
block of statements

Let us see few operations with the help of examples.

Example: Print even and odd numbers between 1 to the entered number.

n = int(input('Please Enter Number '))


while n > 0:
# check even and odd
if n % 2 == 0:
print(n, 'is a even number')
else:
print(n, 'is a odd number')
# decrease number by 1 in each iteration
n = n - 1
Run
Output:

Please Enter Number 7


7 is a odd number
6 is a even number
5 is a odd number
4 is a even number
3 is a odd number
2 is a even number
1 is a odd number
Transfer statements in while loop
Loop control statements change the execution of the normal functioning of the loop.
It is used when you want to exit a loop or skip a part of the loop based on the
given condition. It also knows as transfer statements.

There are three types of loop control statements break, continue and pass.

Break Statement
A break statement terminates the loop containing it. If the break statement is used
inside a nested loop (loop inside another loop), it will terminate the innermost
loop. Let us see the usage of the break statement with an example.

Example: Write a while loop to display each character from a string and if a
character is number then stop the loop.

name = 'Jesaa29Roy'
size = len(name)
i = 0
# iterate loop till the last character
while i < size:
# break loop if current character is number
if name[i].isdecimal():
break;
# print current character
print(name[i], end=' ')
i = i + 1
Run
Output:

J e s a a
Continue Statement

continue is a statement that skips a block of code in the loop for the current
iteration only. It doesn’t terminate the loop but continues in the next iteration
ignoring the loop’s body after it. Let us see the use of the continue statement
with an example.

Example: Write a while loop to display only alphabets from a string.

In this example, we will print only letters from a string by skipping all digits
and special symbols

name = 'Jesaa29Roy'

size = len(name)
i = -1
# iterate loop till the last character
while i < size - 1:
i = i + 1
# skip while loop body if current character is not alphabet
if not name[i].isalpha():
continue
# print current character
print(name[i], end=' ')

====================
Break Statement
A break statement terminates the loop containing it. If the break statement is used
inside a nested loop (loop inside another loop), it will terminate the innermost
loop. Let us see the usage of the break statement with an example.

Example: Write a while loop to display each character from a string and if a
character is number then stop the loop.

name = 'Jesaa29Roy'
size = len(name)
i = 0
# iterate loop till the last character
while i < size:
# break loop if current character is number
if name[i].isdecimal():
break;
# print current character
print(name[i], end=' ')
i = i + 1
=======================

Pass statement is a null statement. Nothing happens when the pass statement is
executed. Primarily it is used in empty functions or classes. When the interpreter
finds a pass statement in the program, it returns no operation. Let us see the
usage of the pass statement with an example.

n = 4
while n > 0:
n = n - 1
pass
===============

Python Training and Exercises : Loops

Table of contents

While loop examples


a = 5

b = 1

while b <= 5:

print ("%d * %d = %d" %(a, b, a*b))

b+=1

----------Output---------

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
=====================

While with “else”


=================================
a = 1

while a <= 3:

b = int (input ("enter a no: "))

if b == 0:

print ("exiting loop with break command, 'else' is not executed")

break

a+=1

else:

print ("loop exited without executing break command")


================================================================

For loop and Range function


for a in range(10):

print (a, end=" ")

----------Output---------

0 1 2 3 4 5 6 7 8 9

a = 5

for b in range(1, 5):

print ("%d * %d = %d" %(a, b, a*b))

----------Output---------

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20

a = [10,20,30,40,50]

for b in a:

print (b+5, end=" ")

----------Output---------

15 25 35 45 55

Python Exercises
1. Write a python program to print the square of all numbers from 0 to 10

2. Write a python program to find the sum of all even numbers from 0 to 10

3. Write a python program to read three numbers (a,b,c) and check how many numbers
between ‘a’ and ‘b’ are divisible by ‘c’

4. Write a python program to get the following output

1-----99

2-----98

3-----97

. .
. .

. .

98-----2

99-----1

5. Write a python program to read a number and print the binary of that number
(hint: if ‘a’ is a string , a[::-1] will be reverse of that string)

6. Write a python program to read four numbers (representing the four octets of an
IP) and print the next five IP address

Eg:

Input:

192 168 255 252

----------Output---------

192 168 255 253

192 168 255 254

192 168 255 255

192 169 0 0

192 169 0 1

7. Write a python program to print the factorial of a given number

8. Write a python program to print the first 10 numbers Fibonacci series

9. Write a python program to read a number and print a right triangle using "*"

Eg :

Input : 5

----------Output---------

* *

* * *

* * * *

* * * * *

10. Write a python program to check given number is prime or not

11. Write a python program to print all prime numbers between 0 to 100 , and print
how many prime numbers are there.
12. a, b, c = 0, 0, 0 . Write a python program to print all permutations using
those three variables

Output : 000 , 001 ,002, 003, 004, 0005 ,006, 007, 008, 009, 010, 011 …… 999
================================================================

You might also like