0% found this document useful (0 votes)
3 views4 pages

Python For Loop Examples and Exercises

Uploaded by

RUDRAKSHA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Python For Loop Examples and Exercises

Uploaded by

RUDRAKSHA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Python 'for' Loop Programs (No Nested Loops)

1. Print numbers from 1 to 10

for i in range(1, 11):

print(i)

2. Print even numbers between 1 and 20

for i in range(2, 21, 2):

print(i)

3. Print the multiplication table of a number

n = 5

for i in range(1, 11):

print(n, 'x', i, '=', n*i)

4. Calculate the sum of first N natural numbers

n = 10

sum = 0

for i in range(1, n+1):

sum += i

print('Sum:', sum)

5. Calculate the factorial of a number

n = 5

fact = 1

for i in range(1, n+1):

fact *= i

print('Factorial:', fact)

6. Print the Fibonacci series up to N terms

n = 10

a, b = 0, 1

for i in range(n):

print(a)

a, b = b, a + b
7. Reverse a string

s = 'hello'

rev = ''

for ch in s:

rev = ch + rev

print('Reversed:', rev)

8. Count vowels in a string

s = 'education'

vowels = 'aeiou'

count = 0

for ch in s:

if ch in vowels:

count += 1

print('Vowels:', count)

9. Find prime numbers from 1 to 50

for num in range(2, 51):

is_prime = True

for i in range(2, int(num**0.5)+1):

if num % i == 0:

is_prime = False

break

if is_prime:

print(num)

10. Print squares of numbers from 1 to 10

for i in range(1, 11):

print(i*i)

11. Sum of digits of a number

n = 1234

sum = 0

for digit in str(n):


sum += int(digit)

print('Sum:', sum)

12. Print ASCII values of characters in a string

s = 'ABC'

for ch in s:

print(ch, ord(ch))

13. Convert string to uppercase using loop

s = 'hello'

res = ''

for ch in s:

res += [Link]()

print(res)

14. Count words in a sentence

s = 'Hello world from Python'

count = 0

for word in [Link]():

count += 1

print('Words:', count)

15. Generate a list of cubes

cubes = []

for i in range(1, 11):

[Link](i**3)

print(cubes)

16. Check if number is palindrome

n = 121

rev = ''

for ch in str(n):

rev = ch + rev

print('Palindrome' if str(n) == rev else 'Not Palindrome')


17. Print characters at even index

s = 'Python'

for i in range(len(s)):

if i % 2 == 0:

print(s[i])

18. Print numbers divisible by 3 from 1 to 30

for i in range(1, 31):

if i % 3 == 0:

print(i)

19. Print characters of string one by one

s = 'loop'

for ch in s:

print(ch)

20. Print all elements in a list

lst = [10, 20, 30, 40]

for item in lst:

print(item)

You might also like