1
Experiment 1
Write a program to demonstrate different number data types in Python.
Source Code:
[Link]
'''Aim:Write a program to demonstrate different number data types in Python.'''
a=10; #Integer Datatype
b=11.5; #Float Datatype
c=2.05j; #Complex Number
print("a is Type of",type(a)); #prints type of variable a
print("b is Type of",type(b)); #prints type of variable b
print("c is Type of",type(c)); #prints type of variable c
Output:
Experiment 2:
Write a program to perform different Arithmetic Operations on numbers in Python.
Source Code:
[Link]
'''Aim:Write a program to perform different Arithmetic Operations on numbers in Python.'''
a=int(input("Enter a value")); #input() takes data from console at runtime as string.
b=int(input("Enter b value")); #typecast the input string to int.
print("Addition of a and b ",a+b);
print("Subtraction of a and b ",a-b);
print("Multiplication of a and b ",a*b);
print("Division of a and b ",a/b);
print("Remainder of a and b ",a%b);
print("Exponent of a and b ",a**b); #exponent operator (a^b)
print("Floar division of a and b ",a//b); # floar division
Output:
2
Experiment 3:
Write a program to create, concatenate and print a string and accessing sub-string from a
given string.
Source Code:
[Link]
''' Aim:Write a program to create, concatenate and print a string and accessing sub-string
from a given string.'''
s1=input("Enter first String : ");
s2=input("Enter second String : ");
print("First string is : ",s1);
print("Second string is : ",s2);
print("concatenations of two strings :",s1+s2);
print("Substring of given string :",s1[1:4]);
Output:
Experiment 4
Write a python script to print the current date in the following format “Sun May 29 02:26:23
IST 2017”
Source Code:
[Link]
'''Aim: . Write a python script to print the current date in the following format Sun May 29
02:26:23 IST 2017 '''
import time;
ltime=[Link]();
print([Link]("%a %b %d %H:%M:%S %Z %Y",ltime)); #returns the formatted time
'''
%a : Abbreviated weekday name.
%b : Abbreviated month name.
%d : Day of the month as a decimal number [01,31].
%H : Hour (24-hour clock) as a decimal number [00,23].
%M : Minute as a decimal number [00,59].
%S : Second as a decimal number [00,61].
%Z : Time zone name (no characters if no time zone exists).
%Y : Year with century as a decimal number.'''
3
Output:
Experiment 5
Write a program to create, append, and remove lists in python.
Source Code:
[Link]
'''Aim: Write a program to create, append, and remove lists in python. '''
pets = ['cat', 'dog', 'rat', 'pig', 'tiger']
snakes=['python','anaconda','fish','cobra','mamba']
print("Pets are :",pets)
print("Snakes are :",snakes)
animals=pets+snakes
print("Animals are :",animals)
[Link]("fish")
print("updated Snakes are :",snakes)
Experiment 6:
Write a program to demonstrate working with tuples in python.
Source Code:
[Link]
'''Write a program to demonstrate working with tuples in python'''
T = ("apple", "banana", "cherry","mango","grape","orange")
print("\n Created tuple is :",T)
print("\n Second fruit is :",T[1])
print("\n From 3-6 fruits are :",T[3:6])
print("\n List of all items in Tuple :")
for x in T:
print(x)
if "apple" in T:
print("\n Yes, 'apple' is in the fruits tuple")
print("\n Length of Tuple is :",len(T))
Output:
4
Experiment 7:
Write a program to demonstrate working with dictionaries in python.
Source Code:
[Link]
'''Write a program to demonstrate working with dictionaries in python.'''
dict1 = {'StdNo':'532','StuName': 'Naveen', 'StuAge': 21, 'StuCity': 'Hyderabad'}
print("\n Dictionary is :",dict1)
#Accessing specific values
print("\n Student Name is :",dict1['StuName'])
print("\n Student City is :",dict1['StuCity'])
#Display all Keys
print("\n All Keys in Dictionary ")
for x in dict1:
print(x)
#Display all values
print("\n All Values in Dictionary ")
for x in dict1:
print(dict1[x])
#Adding items
dict1["Phno"]=85457854
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Change values
dict1["StuName"]="Madhu"
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Removing Items
[Link]("StuAge");
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Length of Dictionary
print("Length of Dictionary is :",len(dict1))
#Copy a Dictionary
5
dict2=[Link]()
#New dictoinary
print("\n New Dictionary is :",dict2)
#empties the dictionary
[Link]()
print("\n Uadated Dictionary is :",dict1)
Output:
6
Experiment 8:
Write a python program to find largest of three numbers.
Source Code:
[Link]
''' Write a python program to find largest of three numbers '''
num1 = int (input ("Enter first number: "))
num2 = int (input ("Enter second number: "))
num3 = int (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:
Experiment 9:
Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [Formula:
c/5 = f-32/9]
Source Code:
[Link]
''' Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
[ Formula: c/5 = f-32/9] '''
print("Options are \n")
print("[Link] temperatures from Celsius to Fahrenheit \n")
print("[Link] temperatures from Fahrenheit to Celsius \n")
opt=int(input("Choose any Option(1 or 2) : "))
if opt == 1:
print("Convert temperatures from Celsius to Fahrenheit \n")
cel = float(input("Enter Temperature in Celsius: "))
fahr = (cel*9/5)+32
print("Temperature in Fahrenheit =",fahr)
elif opt == 2:
print("Convert temperatures from Fahrenheit to Celsius \n")
7
fahr = float(input("Enter Temperature in Fahrenheit: "))
cel=(fahr-32)*5/9;
print("Temperature in Celsius =",cel)
else:
print("Invalid Option")
Output:
Experiment 10 :
Write a Python program to construct the stars (*) pattern, using a nested for loop
Source Code:
[Link]
'''Write a Python program to construct the following pattern, using a nested for loop
*
**
***
****
8
*****
****
***
**
*
'''
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
Output:
Experiment 11:
Write a Python script that prints prime numbers less than 20.
Source Code:
[Link]
'''Write a Python script that prints prime numbers less than 20'''
print("Prime numbers between 1 and 20 are:")
ulmt=20;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
9
print(num)
Output:
Experiment 12 :
Write a python program to find factorial of a number using Recursion.
Source Code:
[Link]
''' Write a python program to find factorial of a number using Recursion.'''
def recur_fact(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_fact(n-1)
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_fact(num))
Output:
10
Experiment 13
Write a program that accepts the lengths of three sides of a triangle as inputs. The program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).
Source Code:
[Link]
'''Write a program that accepts the lengths of three sides of a triangle as inputs. The program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).'''
base=float(input("Enter length of Base : "))
perp=float(input("Enter length of Perpendicular : "))
hypo=float(input("Enter length of Hypotenuse : "))
if hypo**2==((base**2)+(perp**2)):
print("It's a right triangle")
else:
print("It's not a right triangle")
Output:
11
Experiment 14:
Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
Source Code:
[Link]
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end =" ")
a, b = b, a+b
[Link]
'''Write a python program to define a module to find Fibonacci Numbers and import the
module to another program'''
#import fibonacci module
import fibonacci
num=int(input("Enter any number to print Fibonacci series "))
[Link](num)
Output:
Experiment 15:
Write a python program to define a module and import a specific function in that module to
another program.
Source Code:
[Link]
''' Arithmetic Operations Module with Multiple functions'''
def Add(a,b):
c=a+b
return c
def Sub(a,b):
c=a-b
return c
def Mul(a,b):
c=a*b
return c
12
[Link]
'''Write a python program to define a module and import a specific function in that
module to another program.'''
from arth import Add
num1=float(input("Enter first Number : "))
num2=float(input("Enter second Number : "))
print("Addition is : ",Add(num1,num2))
print("Subtraction is : ",Sub(num1,num2)) #gives error:Not importing Sub function from arth
Module
Output:
Experiment 16:
Write a script named [Link]. This script should prompt the user for the names of two text
files. The contents of the first file should be input and written to the second file.
Source Code:
[Link]
This is python program
welcome to python
[Link]
'''Write a script named [Link]. This script should prompt the user for the names of two
text files. The contents of the first file should be input and written to the second
file'''
file1=input("Enter First Filename : ")
file2=input("Enter Second Filename : ")
# open file in read mode
fn1 = open(file1, 'r')
# open other file in write mode
fn2 = open(file2, 'w')
13
# read the content of the file line by line
cont = [Link]()
#type(cont)
for i in range(0, len(cont)):
[Link](cont[i])
# close the file
[Link]()
print("Content of first file copied to second file ")
# open file in read mode
fn2 = open(file2, 'r')
# read the content of the file
cont1 = [Link]()
# print the content of the file
print("Content of Second file :")
print(cont1)
# close all files
[Link]()
[Link]()
Output:
Experiment 17:
14
Write a program that inputs a text file. The program should print all of the unique words in
the file in alphabetical order.
Source Code:
[Link]
This is python program
welcome to python
[Link]
'''Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order'''
fname = input("Enter file name: ")
fh = open(fname)
lst = list() # list for the desired output
words=[];
for line in fh: # to read every line of file [Link]
words += [Link]()
[Link]()
# display the sorted words
print("The unique words in alphabetical order are:")
for word in words:
if word in lst: # if element is repeated
continue # do nothing
else: # else if element is not in the list
[Link](word)
print(word)
#print(lst)
Output:
Experiment 18:
15
Write a Python class to convert an integer to a roman numeral.
Source Code:
[Link]
'''Write a Python class to convert an integer to a roman numeral.'''
class irconvert:
num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),(50, 'L'),
(40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
def num2roman(self,num):
roman = ''
while num > 0:
for i, r in self.num_map:
while num >= i:
roman += r
num -= i
return roman
num=int(input("Enter any Number :"))
print("Roman Number is : ",irconvert().num2roman(num))
Output:
Experiment 19
Write a Python class to implement pow(x, n)
Source Code:
[Link]
'''Write a Python class to implement pow(x, n)'''
class py_pow:
def powr(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
16
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/[Link](x,-n)
val = [Link](x,n//2)
if n%2 ==0:
return val*val
return val*val*x
x=int(input("Enter x value :"))
n=int(input("Enter n value :"))
print("pow(x,n) value is :",py_pow().powr(x,n));
Output:
Experiment 20
Write a Python class to reverse a string word by word.
Source Code:
[Link]
''' Write a Python class to reverse a string word by word. '''
class py_reverse:
def revr(self, strs):
sp=[Link]()
[Link]()
res=" ".join(sp)
return res
str1=input("Enter a string with 2 or more words : ")
print("Reverse of string word by word: \n",py_reverse().revr(str1));
Output:
17