Uploaded by Abhishek Chaudhary

PYTHON

advertisement
DAV INSTITUTE OF ENGINEERING AND
TECHNOLOGY
JALANDHAR
PROGRAMMING IN PYTHON
PRACTICAL FILE
SUBMITTED TODr. Harpreet Bajaj
Dept. of CSE
SUBMITTED BYDivyanshu Kalra
B.Tech CSE
5TH semester
Roll No. : 116/21
Univ. Reg. No. :2103019
Programming in Python
119/21
LIST OF EXPERIMENTS
Task 1: Write a program to demonstrate different number data types in Python.
Task 2: Write a program to perform different Arithmetic Operations on
numbers in Python.
Task 3: Write a program to create, concatenate and print a string and accessing
sub-string from a given string.
Task 4: Write a python script to print the current date in the following format
“Sun May 29 02:26:23 IST 2017”
Task 5: Write a program to create, append, and remove lists in python.
Task 6: Write a program to demonstrate working with tuples in python.
Task 7: Write a program to demonstrate working with dictionaries in python.
Task 8: Write a python program to find largest of three numbers.
Task 9: Write a Python program to convert temperatures to and from Celsius,
Fahrenheit. [ Formula: c/5 = f-32/9]
Task 10: Write a Python program to construct the following pattern, using a
nested for loop
*
*
**
***
****
***
**
*
*
Task 11: Write a Python script that prints prime numbers less than 20.
Task 12: Write a python program to find factorial of a number using
Recursion.
2
Programming in Python
119/21
Task 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).
Task 14: Write a python program to define a module to find Fibonacci
Numbers and import the module to another program.
Task 15: Write a python program to define a module and import a specific
function in that module to another program.
Task 16: Write a script named copyfile.py. 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.
Task 17: Write a program that inputs a text file. The program should print all
of the unique words in the file in alphabetical order.
Task 18: Write a Python class to convert an integer to a roman numeral.
Task 19: Write a Python class to implement pow(x, n)
Task 20: Write a Python class to reverse a string word by word
Task 1: Write a program to demonstrate different number data
types in Python.
3
Programming in Python
119/21
x = 20 #int
print(x,":",type(x))
x = 20.5 #float
print(x,":",type(x))
x = 1j
#complex
print(x,":",type(x))
#String
x = "DAVIET"
print(x,":",type(x))
x = ["Go", "Edu", "Hub"]
print(x,":",type(x))
#list
x = ("Programming", "with", "python")
print(x,":",type(x))
#tuple
x = {"name" : "abc", "age" : 36} #dict
print(x,":",type(x))
x = True #bool
print(x,":",type(x))
x = b"Hello" #bytes
print(x,":",type(x))
x = {"dl", "python", "ml"} #set
print(x,":",type(x))
Output:
4
Programming in Python
119/21
5
Programming in Python
119/21
Task 2: Write a program to perform different Arithmetic
Operations on numbers in Python.
num1=eval(input("enter first number"))
num2=eval(input("enter second number"))
addition=num1+num2
subtraction=num1-num2
multiplication=num1*num2
division=num1/num2
print("different Arithmetic Operations on numbers in Python")
print("addition:",addition)
print("subtraction:",subtraction)
print("multiplication:",multiplication)
print("division:",division)
Output:
6
Programming in Python
119/21
Task 3: Write a program to create, concatenate and print a string
and accessing sub-string from a given string.
str1 = input("Enter the First String : ")
str2 = input("Enter the Second String : ")
concat1 = str1 + str2
print("The Final String After Python String Concatenation = ", concat1)
concat2 = str1 + ' ' + str2
print("The Final After String Concatenation with Space = ", concat2)
text = concat2[8:]
print("substring using[8:] is :",text)
a = concat2.find("in")
print("finding the word 'in ' in the string",a)
Output:
7
Programming in Python
119/21
Task 4: Write a python script to print the current date in the
following format “Sun May 29 02:26:23 IST 2017”
import time;
ltime=time.localtime();
print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime))
'''
%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.
'''
Output:
8
Programming in Python
119/21
Task 5: Write a program to create, append, and remove lists in
python.
#creating lists
pets = ['cat', 'dog', 'rat', 'pig', 'tiger']
#first list
snakes=['python','anaconda','fish','cobra','mamba']
#second list
#printing the lists
print("Pets are :",pets)
print("Snakes are :",snakes)
#appending lists
animals=pets+snakes
print("Animals are :",animals)
#removing element of list
snakes.remove("fish")
#printing the updated list
print("updated Snakes are :",snakes)
Output:
9
Programming in Python
119/21
Task 6: Write a program to demonstrate working with tuples in
python.
#creating tuple
T = ("apple", "banana", "cherry","mango","grape","orange")
#printing the whole tuple
print("\n Created tuple is :",T)
#printing one particular element
print("\n Second fruit is :",T[1])
#printing certain elements
print("\n From 3-6 fruits are :",T[3:6])
#printing all the elements
print("\n List of all items in Tuple :")
for x in T:
print(x)
#checking a certain element
if "apple" in T:
print("\n Yes, 'apple' is in the fruits tuple")
#lenght of tuple
print("\n Length of Tuple is :",len(T))
10
Programming in Python
119/21
OUTPUT:
11
Programming in Python
119/21
Task 7: Write a program to demonstrate working with
dictionaries in python.
#creating dict
dict1 = {'StdNo':'532','StuName': 'abc', '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["Phone_no."]=9876543210
#Updated dictoinary
print("\n Updadated Dictionary after adding new item is :",dict1)
#Change values
dict1["StuName"]="cde"
#Updated dictoinary
print("\n Updadated Dictionary after changing value is :",dict1)
#Removing Items
dict1.pop("StuAge");
#Updated dictoinary
print("\n Updated Dictionary after removing item is :",dict1)
#Length of Dictionary
print("Length of Dictionary is :",len(dict1))
#Copy a Dictionary
12
Programming in Python
119/21
dict2=dict1.copy()
#New dictoinary
print("\n New Dictionary is :",dict2)
#empties the dictionary
dict1.clear()
print("\n Updated Dictionary after deleting items is :",dict1)
OUTPUT:
13
Programming in Python
119/21
Task 8: 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:
14
Programming in Python
119/21
Task 9: Write a Python program to convert temperatures to and
from Celsius, Fahrenheit. [ Formula: c/5 = f-32/9]
print("Options are \n")
print("1.Convert temperatures from Celsius to Fahrenheit \n")
print("2.Convert 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")
fahr = float(input("Enter Temperature in Fahrenheit: "))
cel=(fahr-32)*5/9;
print("Temperature in Celsius =",cel)
else:
print("Invalid Option")
15
Programming in Python
119/21
OUTPUT:
16
Programming in Python
119/21
Task 10: Write a Python program to construct the following pattern, using
a nested for loop
*
**
***
****
***
**
*
n=4
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:
17
Programming in Python
119/21
Task 11: Write a Python script that prints prime numbers less
than 20.
print("Prime numbers between 1 and 20 are:")
limit=20;
for num in range(limit):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
OUTPUT:
18
Programming in Python
119/21
Task 12: 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:
19
Programming in Python
119/21
Task 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).
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:
20
Programming in Python
119/21
Task 14: Write a python program to define a module to find
Fibonacci Numbers and import the module to another program.
#fibonacci.py
def fibonacci(n):
a, b = 0, 1
print(0,end=" ")
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
# write Fibonacci series up to n
#importing fibonacci module
import fibonacci as fib
num=int(input("Enter any number to print Fibonacci series "))
fib.fibonacci(num)
OUTPUT:
21
Programming in Python
119/21
Task 15: Write a python program to define a module and import a specific
function in that module to another program.
#arithmetic.py
def add(a,b):
print("addition:",a+b)
def sub(a,b):
print("subtraction:",a-b)
def mul(a, b):
print("multiplication:", a *b)
def div(a,b):
print("division:",a/b)
#importing add function from arithmetic.py
from arithmetic import add
num1=float(input("Enter first Number : "))
num2=float(input("Enter second Number : "))
add(num1,num2)
OUTPUT:
22
Programming in Python
119/21
Task 16: Write a script named copyfile.py. 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.txt
This is python program
welcome to python
#task
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')
# read the content of the file line by line
cont = fn1.readlines()
# type(cont)
for i in range(0, len(cont)):
fn2.write(cont[i])
# close the file
fn2.close()
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 = fn2.read()
# print the content of the file
print("Content of Second file :")
print(cont1)
23
Programming in Python
119/21
# close all files
fn1.close()
fn2.close()
OUTPUT:
24
Programming in Python
119/21
Task 17: Write a program that inputs a text file. The program
should print all of the unique words in the file in alphabetical
order.
#file1.txt
This is python program
welcome to python
#task
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 romeo.txt
words += line.split()
words.sort()
# 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
lst.append(word)
print(word)
print("List:",lst)
OUTPUT:
25
Programming in Python
119/21
Task 18: 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:
26
Programming in Python
119/21
Task 19: 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:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.powr(x,-n)
val = self.powr(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:
27
Programming in Python
119/21
Task 20: Write a Python class to reverse a string word by word
class py_reverse:
def revr(self, strs):
sp=strs.split()
sp.reverse()
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:
28
Download