Python While Loop Programs: You Need to Know

While Loop: The while loop is used to repeat a set of statements as long as the condition is true, or while loop is used when we don’t know the number of iterations in advance.
Syntax:
initialization
while (expression):
statement

While loop in Python
1. Write a program to print the numbers from 1 to 10.
CODE
i=1
while i<=10:
    print(i)
    i=i+1
OUTPUT
While Loop
2. Write a program to calculate the sum of numbers from 1 to n.
CODE
n=int(input("Enter Number: "))
i=1
sum=0
while i<=n:
    sum=i+sum
    i=i+1
print("Sum","=",sum)
OUTPUT
While Loop
3. Write a program to calculate the factorial of a given number.
CODE
num=int(input("Enter Number: "))
i=1
factorial=1
while i<=num:
    factorial=i*factorial
    i=i+1
print("Factorial of",num,"=",factorial)
OUTPUT
While Loop
4. Write a program to print all even numbers between 1 to n.
CODE
n=int(input("Enter Number: "))
i=2
while i<=n:
    print(i)
    i=i+2
OUTPUT
While Loop

If Else Important Practical Questions

5. Write a program to print all odd numbers between 1 to n.
CODE
n=int(input("Enter Number: "))
i=1
while i<=n:
    print(i)
    i=i+2
OUTPUT
While Loop
6. Write a program to calculate the sum of even numbers between 1 to n.
CODE
n=int(input("Enter Number: "))
i=2
sum=0
while i<=n:
    sum=i+sum
    i=i+2
print(sum)
OUTPUT
While Loop
7. Write a program to calculate the sum of odd numbers between 1 to n.
CODE
n=int(input("Enter Number: "))
i=1
sum=0
while i<=n:
    sum=i+sum
    i=i+2
print(sum)
OUTPUT
While Loop
8. Write a program to print numbers divisible by 5 from 1 to n.
CODE
n=int(input("Enter Number: "))
i=5
sum=0
while i<=n:
    print(i)
    i=i+5
OUTPUT
While Loop
9. Write a program to print a table of a given number by using a while loop.
CODE
num=int(input("Enter Number: "))
i=1
while i<=10:
    print(num*i)
    i=i+1
OUTPUT
While Loop
10. Write a program to reverse the number.
CODE
num=int(input("Enter Number: "))
reverse=0
while num !=0:
    reverse=reverse*10+num%10
    num2//=10
print(f"The reverse is {reverse}.")
OUTPUT
While Loop
Share your love
Sleepy Expert
Sleepy Expert
Articles: 26

Leave a Reply

Your email address will not be published. Required fields are marked *