If Classnote
If Classnote
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
# 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
# print 10 numbers
i = 1
while i < 10:
print(i)
i= i + 1
======================
mystr = "helloworld"
count = 0
===============================
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:
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.
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:
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.
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.
Output:
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.
if condition :
block of statements
else :
block of statements
Example: Print even and odd numbers between 1 to the entered number.
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.
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
===============
Table of contents
b = 1
while b <= 5:
b+=1
----------Output---------
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
=====================
while a <= 3:
if b == 0:
break
a+=1
else:
----------Output---------
0 1 2 3 4 5 6 7 8 9
a = 5
----------Output---------
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
a = [10,20,30,40,50]
for b in a:
----------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’
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:
----------Output---------
192 169 0 0
192 169 0 1
9. Write a python program to read a number and print a right triangle using "*"
Eg :
Input : 5
----------Output---------
* *
* * *
* * * *
* * * * *
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
================================================================