DEV Community

varatharajan
varatharajan

Posted on

while loop - task

Here are some while loop questions focused on numbers for practice:

Basic Problems :
Print Numbers :
Write a program to print numbers from 1 to 10 using a while loop.
input :

def print_number(no):
    num=1
    while num<=no:
        print(num,end=' ')
        num+=1

print_number(10)

Enter fullscreen mode Exit fullscreen mode

or

no = 1
while no<=10:
    print(no, end=' ')
    no+=1
Enter fullscreen mode Exit fullscreen mode

output :

1 2 3 4 5 6 7 8 9 10

Sum of N Numbers :
Write a program to calculate the sum of the first NN natural numbers using a while loop.
input :

def sum_of_natural_numbers(no):
    sum = 0
    num = 1  
    while num <= no:
        sum =sum + num  
        num += 1  
    return sum

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

result = sum_of_natural_numbers(no)
print("The sum of the first", no, "natural numbers is:", result)
Enter fullscreen mode Exit fullscreen mode

output :

Enter a number: 5
The sum of the first 5 natural numbers is: 15

Even Numbers
Write a program to print all even numbers between 1 and 50 using a while loop.
input :

def even_numbers(num):

    no = 2
    while no<=num:
        print(no, end=' ')
        no+=2

even_numbers(50)
Enter fullscreen mode Exit fullscreen mode

output:

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

Odd Numbers
Write a program to print all odd numbers between 1 and NN.
input:

def print_odd_number(no):
    num=1
    while num<=no:
        print(num, end=" ")
        num+=2
    return no
no=int(input("Enter the number:"))
print_odd_number(no)
Enter fullscreen mode Exit fullscreen mode

output :

Enter the number:50
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49

Reverse Count
Write a program to print numbers from 20 to 1 in reverse order using a while loop.
input:

def print_reverse_number(no):
    num=20
    while num>=no:
        print(num, end=" ")
        num-=1
print_reverse_number(1)
Enter fullscreen mode Exit fullscreen mode

output:

20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Intermediate Problems:

Factorial Calculation
Write a program to calculate the factorial of a given number using a while loop.
input:

def factorial(no):
    num=1
    factorial=1
    while num<=no:
        factorial=factorial*num
        num+=1
    return factorial

no = int(input("Enter the number : "))
print(factorial(no))
Enter fullscreen mode Exit fullscreen mode

output:

Enter the number : 4
24

Top comments (0)