0% found this document useful (0 votes)
7 views3 pages

Python Loops Programs

The document provides Python programs demonstrating the use of while and for loops for various tasks, including reversing numbers, printing even numbers, summing odd numbers, generating multiplication tables, calculating the sum of digits, and identifying prime and perfect numbers. It also includes programs for checking palindromes, printing alphabets, identifying Armstrong and strong numbers, generating Fibonacci sequences, and creating star patterns. Each task is presented with both while and for loop implementations.

Uploaded by

n241066
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)
7 views3 pages

Python Loops Programs

The document provides Python programs demonstrating the use of while and for loops for various tasks, including reversing numbers, printing even numbers, summing odd numbers, generating multiplication tables, calculating the sum of digits, and identifying prime and perfect numbers. It also includes programs for checking palindromes, printing alphabets, identifying Armstrong and strong numbers, generating Fibonacci sequences, and creating star patterns. Each task is presented with both while and for loop implementations.

Uploaded by

n241066
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

Python While & For Loop Programs

1. Reverse numbers
While:
n=int(input()); i=n
while i>=1: print(i); i-=1
For:
for i in range(n,0,-1): print(i)

2. Even numbers
While:
i=2
while i<=n: print(i); i+=2
For:
for i in range(2,n+1,2): print(i)

3. Sum of odd numbers


While:
s=0; i=a
while i<=b:
if i%2!=0: s+=i
i+=1
print(s)
For:
s=0
for i in range(a,b+1):
if i%2!=0: s+=i
print(s)

4. Table
While:
i=1
while i<=10: print(n*i); i+=1
For:
for i in range(1,11): print(n*i)

5. Sum of digits
While:
s=0
while n>0: s+=n%10; n//=10
print(s)
For:
s=0
for d in str(n): s+=int(d)
print(s)

6. Prime numbers
For:
for num in range(2,n+1):
p=True
for i in range(2,num):
if num%i==0: p=False
if p: print(num)

7. Perfect numbers
for num in range(1,n+1):
s=0
for i in range(1,num):
if num%i==0: s+=i
if s==num: print(num)

8. First & last digit


print(str(n)[0], str(n)[-1])

9. Palindrome
if str(n)==str(n)[::-1]: print("Palindrome")

10. Alphabets
for i in range(97,123): print(chr(i))

11. Armstrong
s=0
for d in str(n): s+=int(d)**3
if s==n: print("Armstrong")

12. Strong numbers


import math
for num in range(1,n+1):
s=0
for d in str(num):
s+=[Link](int(d))
if s==num: print(num)

13. Fibonacci
a,b=0,1
for i in range(n):
print(a)
a,b=b,a+b

14. Star pattern


for i in range(1,n+1):
print("*"*i)

You might also like