Python 50 Practice Programs with Code
1. Print 'Hello, World!'
print("Hello, World!")
2. Add two numbers
a = 5
b = 3
print('Sum:', a + b)
3. Swap two numbers
a, b = 5, 10
a, b = b, a
print('a =', a, 'b =', b)
4. Find square root of a number
import math
num = 16
print('Square root:', [Link](num))
5. Calculate area of a triangle
a, b, c = 5, 6, 7
s = (a+b+c)/2
area = (s*(s-a)*(s-b)*(s-c))**0.5
print('Area:', area)
6. Solve quadratic equation
import cmath
a, b, c = 1, 5, 6
d = (b**2) - (4*a*c)
sol1 = (-b - [Link](d))/(2*a)
sol2 = (-b + [Link](d))/(2*a)
print('Solutions:', sol1, sol2)
7. Convert kilometers to miles
km = 5
miles = km * 0.621371
print('%0.2f km = %0.2f miles' % (km, miles))
8. Convert Celsius to Fahrenheit
c = 37
f = (c * 9/5) + 32
print(c, 'C =', f, 'F')
9. Check if a number is positive, negative, or zero
num = -5
if num > 0:
print('Positive')
elif num == 0:
print('Zero')
else:
print('Negative')
10. Check if a number is odd or even
num = 7
if num % 2 == 0:
print('Even')
else:
print('Odd')
11. Find the largest among three numbers
a, b, c = 10, 20, 15
print('Largest:', max(a, b, c))
12. Check leap year
year = 2024
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
print('Leap Year')
else:
print('Not Leap Year')
13. Find factorial of a number
num = 5
fact = 1
for i in range(1, num+1):
fact *= i
print('Factorial:', fact)
14. Generate multiplication table
num = 7
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
15. Print Fibonacci sequence
n = 10
a, b = 0, 1
for i in range(n):
print(a, end=' ')
a, b = b, a+b
16. Check Armstrong number
num = 153
s = sum(int(d)**3 for d in str(num))
print('Armstrong' if s == num else 'Not Armstrong')
17. Find sum of natural numbers
n = 10
print('Sum:', n*(n+1)//2)
18. Display powers of 2
for i in range(10):
print('2^', i, '=', 2**i)
19. Find numbers divisible by another number
nums = range(1, 50)
print([n for n in nums if n % 7 == 0])
20. Convert decimal to binary, octal, and hexadecimal
num = 25
print(bin(num), oct(num), hex(num))
21. Find ASCII value of a character
ch = 'A'
print('ASCII:', ord(ch))
22. Find HCF or GCD
import math
a, b = 54, 24
print('GCD:', [Link](a, b))
23. Find LCM
import math
a, b = 15, 20
print('LCM:', abs(a*b)//[Link](a,b))
24. Simple calculator
a, b = 10, 5
print('Add:', a+b)
print('Sub:', a-b)
print('Mul:', a*b)
print('Div:', a/b)
25. Shuffle a deck of cards
import random, itertools
deck = list([Link](['A','2','3','4','5','6','7','8','9','10','J','Q','K'],['Hearts','Diamo
[Link](deck)
print(deck[:5])