0% found this document useful (0 votes)
24 views

Python While Loop

While loops execute a block of code as long as a condition is true. They are useful for indefinite loops where the number of iterations is unknown. The document provides an example of using a while loop to add the digits of an integer number. It also lists some exercises including using while loops to print even/odd numbers between ranges, convert a decimal number to binary, and count the digits of a given number.

Uploaded by

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

Python While Loop

While loops execute a block of code as long as a condition is true. They are useful for indefinite loops where the number of iterations is unknown. The document provides an example of using a while loop to add the digits of an integer number. It also lists some exercises including using while loops to print even/odd numbers between ranges, convert a decimal number to binary, and count the digits of a given number.

Uploaded by

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

Let’s Learn Python

PYTHON WHILE LOOPS


& PROGRAMS

Naveen kumar
While Loop
➢ while loop : Executes a group of statements as long as condition is True
➢ Good for indefinite loops (repeat an unknown number of times)

➢ Syntax:
while condition:
statements

➢ Example:

number = 1 # initial value


while number < 5: # condition
print(number)
number = number + 1 # incrementing

# output
1 2 3 4
Example:
# Add the digits of integer number

n = 1234
temp_n = 0 # initialize the value
while n > 0: # condition
rem = n%10 # reminder of number
temp_n = temp_n + rem # add initialized value + reminder
n = n//10 # divide by 10 to eliminate the last value
print(“Addition of 1234 is ”, temp_n)
Exercise
➢ Write a program to print even numbers between 5 and 20
➢ Write a program to print odd numbers between 5 and 20
➢ Write a program to convert decimal to binary of the given number
➢ Write a program to count number of digits of the given number

You might also like