DEV Community

Sakthivel V
Sakthivel V

Posted on

For loop in Python

For loop:

  • A for loop is used to repeat a block of code for a fixed number of times

  • To loop through a set of code , we can use the range() function.

  • The range() function increment the sequence by 1, however it is possible to increment the value by adding a third parameter: range(2, 30, 3):

Syntax:

for (variable) in (sequence):
code block

Examples :

  1. # Print 1, 2, 3 … 10
  2. # Print 2, 4 ,6 … 20
  3. # Print Table given a number a. Ex: 2 -> 1x2, 2x2, 3x2 … 10x2
  4. # Find all odd numbers until given number a. Ex: 10 -> 1, 3, 5, 7, 9
  5. # Find all numbers divisible by 3 until given number a. Ex: 10 -> 3, 6, 9
  6. # Find all numbers divisible by 3 and 5 until given number a. Ex: 50 -> 15, 30, 45
  7. # Sum of natural numbers until given number a. Ex: input: 4 -> 1 + 2 + 3 + 4 -> 10
  8. # Find factorial of given number a. Ex: input 5 -> 5 * 4 * 3 * 2 * 1 -> 120

Answers:

1).

def print_1_10():
for i in range(1,11):
print(i)
print_1_10()

2).

def print_2_20():
for i in range(2,22,2):
print(i)
print_2_20()

3).

def print_table():
for i in range(1,11):
print(i*2)
print_table()

4).

def print_odd(n):
for i in range(1,n+1):
if(i%2!=0):
print (i)
n=int(input("Enter a number: "))
print_odd(n)

5).

n=int(input("Enter a number: "))
def print_div_by_3(n):
for i in range(1,n+1):
if(i%3==0):
print (i)
print_div_by_3(n)

6).

def print_div_by_3_and_5(n):
for i in range(1,n+1):
if(i%3==0 and i%5==0):
print (i)
n=int(input("Enter a number: "))
print_div_by_3_and_5(n)

7).

n=int(input("Enter a number: "))
def print_sum(n):
sum=0
for i in range(1,n+1):
sum = sum + i
print(sum)
print_sum(n)

8).

def print_fact(n):
fact=1
for i in range(1,n+1):
fact = fact * i
print(fact)
n=int(input("Enter a number: "))
print_fact(n)

*References: *

https://www.w3schools.com/Python/python_for_loops.asp
https://www.geeksforgeeks.org/python/python-for-loops/

Top comments (0)