For Loop Programs in Python: Important for O Level Exam

For loop in Python

For Loop Statement: The for loop is used to repeat a set of statements when the number of cycles is known in advance. In other words, the for loop statement is used to repeat a statement or a block of statements a specified number of times.

1. Write a program to print numbers from 1 to 10.
CODE
for i in range (1,11):
    print(i)
OUTPUT
For Loop Programs in Python
2. Write a program to calculate the sum of all integers from 1 to n.
CODE
n=int(input("Enter Number: "))
sum=sum(range(1,n+1))
print("Sum","=",sum)
OUTPUT
For Loop
3. Write a program to calculate the factorial of a given number.
CODE
n=int(input("Enter Number: "))
factorial=1
for i in range (1,n+1):
    factorial=factorial*i
print("Factorial of",n,"=",factorial)
OUTPUT
For Loop
4. Write a program to calculate the sum of even numbers between 1 to n.
CODE
n=int(input("Enter Number: "))
sum=sum(i for i in range (1,n+1) if i%2==0)
print("Sum of even numbers","=",sum)
OUTPUT
For Loop
5. Write a program to calculate the sum of odd numbers between 1 to n.
CODE
n=int(input("Enter Number: "))
sum=sum(i for i in range (1,n+1) if i%2!=0)
print("Sum of odd numbers","=",sum)
OUTPUT
For Loop
6. Write a program to reverse the numbers from 1 to 10.
CODE
for i in range (10,0,-1):
    print(i)
OUTPUT
For Loop

Important if-else statements Questions

7. Write a program to print numbers from 1 to 50 at the interval of 3.
CODE
for i in range (1,50,3):
    print(i)
OUTPUT
For Loop
8. Write a program to print the Fibonacci series up to n terms.
CODE
n=int(input("Enter a number: "))
a,b=0,1
for i in range(n):
    print(a,end="  ")
    a,b=b,a+b
OUTPUT
For Loop
9. Write a program to generate a number in a triangle pattern.
CODE
n=int(input("Enter the number of row: "))
for i in range(1,n+1):
    print(" ".join(str(j)for j in range(1,i+1)))
OUTPUT
For Loop
10. Write a program to print squares of numbers from 1 to n.
CODE
n=int(input("Enter Number: "))
for i in range (1,n+1):
    print(i*i)
OUTPUT
For Loop
11. Write a program to find the sum of the first n squares.
CODE
n=int(input("Enter Number: "))
sum=sum(i**2 for i in range(1,n+1))
print(f"The sum of squares is = {sum}")
OUTPUT
For Loop
12. Write a program to find the sum of cubes of the first n numbers.
CODE
n=int(input("Enter Number: "))
sum=sum(i**3 for i in range(1,n+1))
print(f"The sum of cubes is = {sum}")
OUTPUT
For Loop
Share your love
Sleepy Expert
Sleepy Expert
Articles: 26

Leave a Reply

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