Complete Guide For Python Programming (2015)
PYTHON PROGRAMS
Python 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]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
Output:
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
Python Program to Add Two Numbers
# This program adds two numbers
# Numbers are provided by the user
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
Output:
Enter first number: 5.3
Enter second number: 3.3
The sum of 5.3 and 3.3 is 8.6
Python Program to Calculate the Area of a Triangle
# Python Program to find the area of triangle
# Three sides of the triangle
# a,b,c are provided by the user
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semiperimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(sa)*(sb)*(sc)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Output:
Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is 14.70
Python Program to Check Armstrong Number
# Python program to if the
# number provided by the
# user is an Armstrong number
# or not
# take input from the user
num = int(input("Enter a number: "))
# initialise sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output 1
Enter a number: 663
663 is not an Armstrong number
Output 2
Enter a number: 371
407 is an Armstrong number
Python Program to Check if a Number is Odd or Even
# Python program to check if
# the input number is odd or even.
# A number is even if division
# by 2 give a remainder of 0.
# If remainder is 1, it is odd.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Output 1
Enter a number: 73
73 is Odd
Output 2
Enter a number: 24
24 is Even
Python Program to Check if a Number is Positive, Negative or Zero
# In this python program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use 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 1
Enter a number: 5
Positive number
Output 2
Enter a number: 0
Zero
Output 3
Enter a number: 4
Negative number
Python Program to Check if a String is Palindrome or Not
# Program to check if a string
# is palindrome or not
# take input from the user
my_str = input("Enter a string: ")
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")
Output 1
Enter a string: aIbohPhoBiA
It is palindrome
Output 2
Enter a string: 13344331
It is palindrome
Output 3
Enter a string: palindrome
It is not palindrome
Python Program to Check Leap Year
# Python program to check if
# the input year is
# a leap year or not
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output 1
Enter a year: 2012
2012 is a leap year
Output 2
Enter a year: 2015
2015 is not a leap year
Python Program to Check Prime Number
# Python program to check if
# the input number is
# prime or not
# take input from the user
num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
Output 1
Enter a number: 407
407 is not a prime number
11 times 37 is 407
Output 2
Enter a number: 853
853 is a prime number
Python Program to Convert Celsius To Fahrenheit
# Python Program to convert temperature in
# celsius to fahrenheit where, input is
# provided by the user in
# degree celsius
# take input from the user
celsius = float(input('Enter degree Celsius: '))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Output
Enter degree Celsius: 43.7
43.7 degree Celsius is equal to 110.66 degree Fahrenheit
Python Program to Convert Decimal into Binary, Octal and Hexadecimal
# Python program to convert decimal
# number into binary, octal and
# hexadecimal number system
# Take decimal number from user
dec = int(input("Enter an integer: "))
print("The decimal value of",dec,"is:")
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
Output
Enter an integer: 133
The decimal value of 133 is:
0b10000101 in binary.
0o205 in octal.
0x85 in hexadecimal.
Python Program to Convert Decimal to Binary Using Recursion
# Python program to convert decimal
# number into binary number
# using recursive function
def binary(n):
"""Function to print binary number
for the input decimal using recursion"""
if n > 1:
binary(n//2)
print(n % 2,end = '')
# Take decimal number from user
dec = int(input("Enter an integer: "))
binary(dec)
Output
Enter an integer: 76
1001100
Python Program to Convert Kilometers to Miles
# Program to convert kilometers
# into miles where, input is
# provided by the user in
# kilometers
# take input from the user
kilometers = float(input('How many kilometers?: '))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))
Output
How many kilometers?: 3.7
5.500 kilometers is equal to 2.300 miles
Python Program to Count the Number of Each Vowel
# Program to count the number of
# each vowel in a string
# string of vowels
vowels = 'aeiou'
# take input from the user
ip_str = input("Enter a string: ")
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Output
Enter a string: I welcome you all to read my book and learn python easily.
{'e': 4, 'u': 1, 'o': 6, 'a': 5, 'i': 1}
Python Program to Display Calendar
# Python program to display calendar
# of given month of the year
# import module
import calendar
# ask of month and year
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy,mm))
Output
Enter year: 2015
Enter month: 09
September 2015
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 
Python Program to Display Fibonacci Sequence Using Recursion
# Python program to display the Fibonacci
# sequence up to nth term using
# recursive functions
def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n1) + recur_fibo(n2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Output
How many terms? 8
Fibonacci sequence:
0
1
1
2
3
5
8
13
Python Program To Display Powers of 2 Using Anonymous Function
# Python Program to display
# the powers of 2 using
# anonymous function
# Take number of terms from user
terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
for i in range(terms):
print("2 raised to power",i,"is",result[i])
Output
How many terms? 6
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
Python Program to Display the multiplication Table
# Python program to find the multiplication
# table (from 1 to 10)c
# of a number input by the user
# take input from the user
num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
Output
Display multiplication table of? 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Python Program to Find Armstrong Number in an Interval
# Program to ask the user
# for a range and display
# all Armstrong numbers in
# that interval
# take input from the user
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num)
Output
Enter lower range: 0
Enter upper range: 999
0
1
153
370
371
407
Python Program to Find ASCII Value of Character
# Program to find the
# ASCII value of the
# given character
# Take character from user
c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))
Output 1
Enter a character: k
The ASCII value of 'k' is 107
Output 2
Enter a character: =
The ASCII value of '=' is 61
Python Program to Find Factorial of Number Using Recursion
# Python program to find the
# factorial of a number
# using recursion
def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Output 1
Enter a number: 5
Sorry, factorial does not exist for negative numbers
Output 2
Enter a number: 5
The factorial of 5 is 120
Python Program to Find Factors of Number
# Python Program to find the
# factors of a number
# define a function
def print_factors(x):
"""This function takes a
number and prints the factors"""
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
# take input from the user
num = int(input("Enter a number: "))
print_factors(num)
Output
Enter a number: 120
The factors of 120 are:
1
2
3
4
5
6
8
10
12
15
20
24
30
40
60
120
Python Program to Find Hash of File
# Python rogram to find the SHA1
# message digest of a file
# import hashlib module
import hashlib
def hash_file(filename):
""""This function returns the SHA1 hash
of the file passed into it"""
# make a hash object
h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest
return h.hexdigest()
message = hash_file("track1.mp3")
print(message)
Output
633d7356947eec543c50b76a1852f92427f4dca9
Python Program to Find HCF or GCD
# Python program to find the
# H.C.F of two input number
# define a function
def hcf(x, y):
"""This function takes two
integers and returns the H.C.F"""
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2))
Output
Enter first number: 40
Enter second number: 48
The H.C.F. of 40 and 48 is 8
Python Program to Find LCM
# Python Program to find the
# L.C.M. of two input number
# define a function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
Output
Enter first number: 3
Enter second number: 4
The L.C.M. of 3 and 4 is 12
Python Program to Find Numbers Divisible by Another Number
# Python Program to find numbers
# divisible by thirteen
# from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
Output
Numbers divisible by 13 are [65, 39, 221]
Python Program to Find Sum of Natural Numbers Using Recursion
# Python program to find the sum of
# natural numbers up to n
# using recursive function
def recur_sum(n):
"""Function to return the sum
of natural numbers using recursion"""
if n <= 1:
return n
else:
return n + recur_sum(n1)
# take input from the user
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Output
Enter a number: 10
The sum is 55
Python Program to Find the Factorial of a Number
# Python program to find the
# factorial of a number
# provided by the user
# take input from the user
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output 1
Enter a number: 18
Sorry, factorial does not exist for negative numbers
Output 2
Enter a number: 9
The factorial of 9 is 362,880
Python Program to Find the Largest Among Three Numbers
# Python program to find the largest
# number among the three
# input numbers
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
Output 1
Enter first number: 8
Enter second number: 16
Enter third number: 4
The largest number is 16.0
Output 2
Enter first number: 6
Enter second number: 15
Enter third number: 0
The largest number is 0.0
Python Program to Find the Size (Resolution) of Image
# Python Program to find the resolution
# of a jpeg image without using
# any external libraries
def jpeg_res(filename):
""""This function prints the resolution
of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("image.jpg")
Output
The resolution of the image is 180 x 200
Python Program to Find the Square Root
# Python Program to calculate the square root
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Output
Enter a number: 11
The square root of 11.000 is 3.316
Python Program to Find the Sum of Natural Numbers
# Python program to find the sum of
# natural numbers up to n
# where n is provided by user
# take input from the user
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num = 1
print("The sum is",sum)
Output
Enter a number: 10
The sum is 55
Python Program to Generate a Random Number
# Program to generate a random number
# between 0 and 9
# import the random module
import random
print(random.randint(0,9))
Output
5
Python Program to Illustrate Different Set Operations
# Program to perform different
# set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# 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)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
Output
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
Python Program to Make a Simple Calculator
# Program make a simple calculator
# that can add, subtract, multiply
# and divide using functions
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x  y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 2
Enter first number: 20
Enter second number: 11
20  11 = 9
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]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Output
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Python Program to Print all Prime Numbers in an Interval
# Python program to ask the user
# for a range and display
# all the prime numbers in
# that interval
# take input from the user
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Output
Enter lower range: 100
Enter upper range: 200
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
Python Program to Print Hi Good Morning!
# This program prints Hi, Good Morning!
print('Hi, Good Morning!')
Output
Hi, Good Morning!
Python program to Print the Fibonacci sequence
# Program to display the fibonacci
# sequence up to nth tern where
# n is provided by the user
# take input from the user
nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=' , ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
Output
How many terms? 12
Fibonacci sequence:
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89
Python Program to Remove Punctuations form a String
# Program to all punctuations from the
# string provided by the user
# define punctuations
punctuations = '''!()[]{};:'"\,<>./?@#$%^&*_~'''
# take input from the user
my_str = input("Enter a string: ")
# remove punctuations from the string
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)
Output
Enter a string: "Hello!!!", Good Morning Have a good day.
Hello Good Morning Have a good day
Python Program to Shuffle Deck of Cards
# Python program to shuffle a
# deck of card using the
# module random and draw 5 cards
# import modules
import itertools, random
# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
# shuffle the cards
random.shuffle(deck)
# draw five cards
print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])
Output 1
You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade
Output 2
You got:
10 of Club
1 of Heart
3 of Diamond
2 of Club
3 of Club
Python Program to Solve Quadratic Equation
# Solve the quadratic equation
# ax**2 + bx + c = 0
# a,b,c are provied by the user
# import complex math module
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2)  (4*a*c)
# find two solutions
sol1 = (bcmath.sqrt(d))/(2*a)
sol2 = (b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (3+0j) and (2+0j)
Python Program to Sort Words in Alphabetic Order
# Program to sort alphabetically the words
# form a string provided by the user
# take input from the user
my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
Output
Enter a string: this is my second python book to read
book
is
my
python
read
second
this
to
Python Program to Swap Two Variables
# Python program to swap two variables
# provided by the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable
# and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output
Enter value of x: 8
Enter value of y: 15
The value of x after swapping: 15
The value of y after swapping: 8
Python Program to Transpose a Matrix
# Program to transpose a matrix
# using nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
Output
[12, 4, 3]
[7, 5, 8]