Python Practice Programs
Python Practice Programs
Example: vi add.py
Example. vi area.py
Example programs
To print HELLO WORLD
# This program prints Hello, world!
print('Hello, world!')
num1 = 1.5
num2 = 6.3
Output
Output
Output
num = 1+2j
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.
format(num ,num_sqrt.real,num_sqrt.imag))
Output
a = 5
b = 6
c = 7
Output
print(random.randint(0,9))
Run Code
Output
5
Kilometers to Miles
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
Output
a = 1
b = 5
c = 6
Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit'
%(celsius,fahrenheit))
Run Code
Output
x = 5
y = 10
Output
The value of x after swapping: 10
The value of y after swapping: 5
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
x = x + y
y = x - y
x = x - y
x = x * y
y = x / y
x = x / y
XOR swap
This algorithm works for integers only
x = x ^ y
y = x ^ y
x = x ^ y
Using if...elif...else
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output
Enter a number: 2
Positive number
Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output
Enter a number: 0
Zero
Output 1
Enter a number: 43
43 is Odd
Output 2
Enter a number: 18
18 is Even
num1 = 10
num2 = 14
num3 = 12
Output
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Run Code
Output
print('Hello, world!')
num1 = 1.5
num2 = 6.3
Output
Output
Output
num = 1+2j
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.
format(num ,num_sqrt.real,num_sqrt.imag))
Output
a = 5
b = 6
c = 7
Output
print(random.randint(0,9))
Run Code
Output
5
Kilometers to Miles
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
Output
a = 1
b = 5
c = 6
Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
convert temperature in Celsius to Fahrenheit
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit'
%(celsius,fahrenheit))
Run Code
Output
x = 5
y = 10
Output
The value of x after swapping: 10
The value of y after swapping: 5
Swap two numbers Without Using Temporary Variable
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
x = x + y
y = x - y
x = x - y
x = x * y
y = x / y
x = x / y
XOR swap
This algorithm works for integers only
x = x ^ y
y = x ^ y
x = x ^ y
Check if a Number is Positive, Negative or 0
Using if...elif...else
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output
Enter a number: 2
Positive number
Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output
Enter a number: 0
Zero
Check if a Number is Odd or Even
A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
Output 1
Enter a number: 43
43 is Odd
Output 2
Enter a number: 18
18 is Even
Output
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Output
Output
Output
factorial = 1
Output
num = 12
Output
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Program to display the Fibonacci sequence up to n-th
term
Output
# initialize sum
sum = 0
Output 1
Output 2
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
Output
Output
Output
Output
c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))
Output
# define a function
def compute_hcf(x, y):
num1 = 54
num2 = 24
Output
The H.C.F. is 6
Program to Find LCM
# Python Program to find the L.C.M. of two input number
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 54
num2 = 24
Output
num = 320
print_factors(num)
Output
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
else:
print("Invalid Input")
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
Program to Shuffle Deck of Cards
# Python program to shuffle a deck of card
# importing modules
import itertools, random
Output
You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade
Program to Display Calendar
# Program to display calendar of the given month and year
yy = 2014 # year
mm = 11 # month
Output
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Program to Display Fibonacci
Sequence Using Recursion
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
Output
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Program to Find Sum of Natural
Numbers Using Recursion
# Python program to find the sum of natural using recursive function
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Output
def recur_factorial(n):
if n == 1:
return n
else:
return n * recur_factorial(n-1)
num = 7
Output
# decimal number
dec = 34
convertToBinary(dec)
print()
Output
100010
Program to Add Two Matrices
# Program to add two matrices using nested loop
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
Output
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
Python Program to Transpose a
Matrix
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for r in result:
print(r)
Output
[12, 4, 3]
[7, 5, 8]
Python Program to Multiply Two
Matrices
# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for r in result:
print(r)
Output
my_str = 'aIbohPhoBiA'
my_str = my_str.casefold()
Output
Output
Output
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
Output
# string of vowels
vowels = 'aeiou'
print(count)
Output
* *
* * *
* * * *
* * * * *
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
Python Program to Merge Two
Dictionaries
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print(dict_1 | dict_2)
Run Code
Output
Output
0 21
1 44
2 35
3 11
Python Program to Flatten a Nested
List
my_list = [[1], [2, 3], [4, 5, 6, 7]]
Output
[1, 2, 3, 4, 5, 6, 7]
Python Program to Access Index of a
List Using for Loop
my_list = [21, 44, 35, 11]
Output
0 21
1 44
2 35
3 11
Python Program to Sort a Dictionary
by Value
dt = {5:4, 1:6, 6:3}
print(sorted_dt)
Run Code
Output
{6: 3, 5: 4, 1: 6}
Python Program to Iterate Over
Dictionaries Using for Loop
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
Output
a juice
b grill
c corn
Python Program to Check If a List is
Empty
my_list = []
if not my_list:
print("the list is empty")
Run Code
Output
try:
num = int(input())
print(string+num)
except (TypeError, ValueError) as e:
print(e)
Run Code
Input
a
2
Output
Output
[1, 'a', 3, 4, 5]
Python Program to Check if a Key is
Already Present in a Dictionary
my_dict = {1: 'a', 2: 'b', 3: 'c'}
if 2 in my_dict:
print("present")
Run Code
Output
present
Python Program to Split a List Into
Evenly Sized Chunks
def split(list_a, chunk_size):
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
Run Code
Output
Output
<class 'int'>
1500
Example 2: Parse string into float
balance_str = "1500.4"
balance_float = float(balance_str)
Output
<class 'float'>
1500.4
Example 3: A string float numeral into integer
balance_str = "1500.34"
balance_int = int(float(balance_str))
Output
<class 'int'>
1500
Python Program to Convert String to
Datetime
Example 1: Using datetime module
from datetime import datetime
print(type(datetime_object))
print(datetime_object)
Run Code
Output
<class 'datetime.datetime'>
2011-03-11 11:31:00
Example 2: Using dateutil module
from dateutil import parser
print(date_time)
print(type(date_time))
Run Code
Output
2011-03-11 11:31:00
<class 'datetime.datetime'>
Python Program to Get the Last
Element of the List
my_list = ['a', 'b', 'c', 'd', 'e']
Output
e
Python Program to Get a Substring
of a String
my_string = "I love python."
# prints "love"
print(my_string[2:6])
Output
love
love python.
I love python
Python Program to Check If a String
Is a Number (Float)
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
print(isfloat('s12'))
print(isfloat('1.123'))
Run Code
Output
False
True
Python Program to Count the
Occurrence of an Item in a List
freq = ['a', 1, 'a', 4, 3, 2, 'a'].count('a')
print(freq)
Run Code
Output
3
Python Program to Delete an
Element From a Dictionary
Example 1: Using del keyword
my_dict = {31: 'a', 21: 'b', 14: 'c'}
del my_dict[31]
print(my_dict)
Run Code
Output
print(my_dict.pop(31))
print(my_dict)
Run Code
Output
a
{21: 'b', 14: 'c'}
Python Program to Create a Long
Multiline String
Example 1: Using triple quotes
my_string = '''The only way to
learn to program is
by writing code.'''
print(my_string)
Run Code
Output
print(my_string)
Run Code
Output
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
Output
4321
Output
654321
Python Program to Compute the
Power of a Number
Example 1: Calculate power of a number using a while loop
base = 3
exponent = 4
result = 1
while exponent != 0:
result *= base
exponent-=1
Output
Answer = 81
result = 1
Output
Answer = 81
Example 3: Calculate the power of a number using pow() function
base = 3
exponent = -4
Output
Answer = 0.012345679012345678
Python Program to Count the
Number of Digits Present In a
Number
Example 1: Count Number of Digits in an Integer using while loop
num = 3452
count = 0
while num != 0:
num //= 10
count += 1
Output
Number of digits: 4
Output
6
Python Program to Check If Two
Strings are Anagram
str1 = "Race"
str2 = "Care"
else:
print(str1 + " and " + str2 + " are not anagram.")
Run Code
Output
print(my_string[0].upper() + my_string[1:])
Run Code
Output
Programiz is Lit
cap_string = my_string.capitalize()
print(cap_string)
Run Code
Output
Programiz is lit
Python Program to Create a
Countdown Timer
import time
def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)
Python Program to Count the
Number of Occurrence of a
Character in String
Example 1: Using a for loop
count = 0
my_string = "Programiz"
my_char = "r"
for i in my_string:
if i == my_char:
count += 1
print(count)
Run Code
Output
print(my_string.count(my_char))
Run Code
Output
2
Python Program to Remove
Duplicate Element From a List
Example 1: Using set()
list_1 = [1, 2, 1, 4, 6]
print(list(set(list_1)))
Run Code
Output
[1, 2, 4, 6]
print(list(set(list_1) ^ set(list_2)))
Run Code
Output
[4, 6, 7, 8]
Python Program to Iterate Through
Two Lists in Parallel
Example 1: Using zip (Python 3+)
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
Output
1 a
2 b
3 c
Example 2: Using itertools (Python 2+)
import itertools
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
print("\n")
Output
1 a
2 b
3 c
1 a
2 b
3 c
4 None