Numericals of For and While Loop 1
Numericals of For and While Loop 1
HANDOUT
1.Print Numbers from 1 to 10
for i in range(1, 11):
print(i)
2. Calculate the Sum of All Numbers from 1 to N
n = int(input("Enter a number: "))
total = 0
for i in range(1, n + 1):
total += i
print("The sum of numbers from 1 to", n, "is:", total)
3. Print Multiplication Table of a Given Number
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
4. Find the Factorial of a Number
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print("The factorial of", n, "is:", factorial)
5. Print Even Numbers from a List
numbers = [10, 15, 20, 25, 30, 35, 40]
for num in numbers:
if num % 2 == 0:
print(num, "is even")
Here are the same five programs rewritten using while loops:
1. Print Numbers from 1 to 10
i=1
while i <= 10:
print(i)
i += 1
2. Calculate the Sum of All Numbers from 1 to N
n = int(input("Enter a number: "))
total = 0
i=1
while i <= n:
total += i
i += 1
print("The sum of numbers from 1 to", n, "is:", total)
3. Print Multiplication Table of a Given Number
num = int(input("Enter a number: "))
i=1
while i <= 10:
print(f"{num} x {i} = {num * i}")
i += 1
4. Find the Factorial of a Number
n = int(input("Enter a number: "))
factorial = 1
i=1
while i <= n:
factorial *= i
i += 1
print("The factorial of", n, "is:", factorial)
5. Print Even Numbers from a List
numbers = [10, 15, 20, 25, 30, 35, 40]
i=0
while i < len(numbers):
if numbers[i] % 2 == 0:
print(numbers[i], "is even")
i += 1