Python_LabCourseFile20233docx__2024_09_18_12_49_13
Python_LabCourseFile20233docx__2024_09_18_12_49_13
"To emerge as the most preferred educational group with global recognition, developing competent
and socially sensitive leaders committed to excellence."
Institute Mission
To make incessant endeavour to translate our vision into a reality & achieve the following
objectives:
To create world class facilities & ambiance for advance level of teaching and practical
training.
To develop students as global citizens with conscience, commitment & education.
To continuously grow & become fountain head among Institutes of Technical Higher
Education in India.
To strengthen Industry-Institute Interface & promote Entrepreneurial development activities.
To continuously strive for research, development & innovation in all relevant fields, thereby
providing the faculty & students the requisite platform to showcase their talents & win
laurels.
To have collaboration with leading Universities of the world with a view to provide
opportunities to the students for higher studies & seek placement avenues abroad.
To maintain the first position in placements in the North region, thereby ensuring that every
CGCians gets the best possible placement opportunities.
VISION
To provide imperative skills to students for meeting industry needs, and to become responsible
engineers, entrepreneurs and citizens.
MISSION
PEO 1: To impart core theoretical and practical knowledge of Computer applications for leading
successful career in industries, pursuing higher studies orentrepreneurial endeavors.
PEO 2: To develop the ability to critically think, analyze, design and develop software-based
solutions.
PEO 3: To imbibe the life-long learning and understanding of ethical values, their duties toward
environmental issues and sensitize them toward their social responsibilityas software developer.
PSO 1: Able to acquire practical competency with emerging technologies and skillsneeded for
becoming an effective software developer.
PSO 2: Able to assess hardware and software aspects necessary to develop application software.
Program Outcomes (PO’s)
PO1: Basic knowledge: An ability to apply knowledge of basic mathematics, science and domain
knowledge to solve the computational problems.
PO2:Discipline knowledge: An ability to apply discipline –specific knowledge to solve core and/or
applied computational problems.
PO3:Experiments and practice: An ability to plan and perform experiments and practices and to
use the results to solve computational problems.
PO4:Tools Usage: Apply appropriate technologies and tools with an understanding oflimitations.
PO5:Profession and society: Demonstrate knowledge to assess societal, health, safety, legal and
cultural issues and the consequent responsibilities relevantto professional practice.
PO7:Ethics: Apply ethical principles and commit to professional ethics andresponsibilities and
norms of the professional practice.
PO8:Individual and team work: Function effectively as an individual, and as amember or leader
in diverse/multidisciplinary teams.
PO10: Life-long learning: Recognize the need for, and have the preparation andability to engage in
independent and life-long learning in the context oftechnological changes.
PO11:Problem Analysis: Identify, formulate, research literature, and solve complex computing
problem searching substantiated conclusions using fundamental principles of mathematics,
computing sciences, and relevant domain disciplines.
Branch:ComputerApplications Credits:2
Semester:3rd Contacthours:4hoursperweek
Theory/Practical: Practical Percentage of numerical/design problems: 90%
Internalmax.marks:60 Duration of end semester exam (ESE):3hrs
Externalmax.marks:40 Elective status: Core
Total marks: 100
Prerequisite: -NA-
Co requisite: -NA-
Additional material required in ESE: -NA-
Course Outcomes
CO# Course outcomes
CO1 Outline various programming constructs like data types and control structures of Python.
CO2 Implement different data structures
CO3 Implement modules and functions.
CO4 Illustrate concept of object-oriented programming.
CO5 Implement file handling.
SYLLABUS:
S.no. Assignments
1 Computesum,subtraction, multiplication,divisionandexponentof givenvariables input by
the user.
2 Computeareaoffollowingshapes:circle,rectangle,triangle,square,trapezoid
andparallelogram.
3 Computevolumeoffollowing3Dshapes:cube,cylinder,coneand sphere.
4 Compute and print roots of quadratic equationax2+bx+c=0,wherethe valuesofa,b,
andcareinputbythe user.
5 Print numbers upto Nwhicharenotdivisibleby 3,6,9,,e.g., 1, 2,4, 5, 7,….
6 Write a program to determine whether a triangle is isoscelesornot?
7 Printmultiplication tableof anumberinputby the user
8 Computesumofnaturalnumbersfromonetonnumber.
9 PrintFibonacciseries upto nnumbers e.g.01 12358 13…..n
10 Computefactorialof agiven number.
11 Countoccurrenceofadigit5inagivenintegernumberinput by the user.
12 PrintGeometricand Harmonicmeansof aseriesinputbythe user.
13 Evaluatethefollowingexpressions:
x-x2 /2!+x3 /3!-x 4 /4!+…xn /n
b.!b. x-x 3/3!+x5 /5!-x 7/7!+… xn /n!
14 Printallpossiblecombinationsof4,5,and6.
15 Determineprimenumberswithin aspecificrange.
16 Count number of persons of age above 60 and below90
17 Computetransposeofa matrix.
18 Performfollowingoperationsontwomatrices.1)Addition2)Subtraction
3)Multiplication
19 Countoccurrenceofvowels
20 Counttotalnumberofvowelsin aword.
21 Determinewhetherastring ispalindromeornot.
22 Perform following operations on a list of numbers:
1)Insertanelement2)deleteanelement3)sortthelist4)deleteentirelist
23 DisplaywordafterSortinginalphabeticalorder
24 Performsequentialsearch onalistof givennumbers.
25 Performsequentialsearchonorderedlistofgivennumbers.
26 Maintainpracticalnotebookaspertheirserialnumbersinlibrary
usingPythondictionary
27 Performfollowingoperationsondictionary1)Insert2)delete3) change
28 Checkwhetheranumberisinagivenrangeusingfunctions.
29 Write a Python function that accepts a string andcalculatesnumberofuppercaseletters
andlowercaselettersavailable in that string.
30 TofindtheMaxofthreenumbersusingfunctions.
31 Multiplyall thenumbers inalistusing functions.
32 SolvetheFibonaccisequenceusingrecursion.
33 Get the factorial of a non-negative integer usingrecursion.
34 WriteaprogramtocreateamoduleoffactorialinPython.
35 Design a Python class named Rectangle, constructedby a length &width, also design a
method which willcomputethe areaofarectangle.
36 Design a Python class named Circle constructed by aradius and two methods which
will compute the areaandthe perimeter ofacircle.
37 DesignaPythonclasstoreverseastring‘wordbyword’.
38 WriteaPythonprogram toreadanentiretextfile.
39 DesignaPythonprogramtoreadfirstnlinesofatextfile.
40 ConstructaPythonprogramtowriteandappendtexttoa fileand display thetext.
Text Books
ReferenceBooks:
1. Python, The complete Reference, Martin C. Brown, Mc Graw HillEducation.
2. Python in a Nutshell, A. Martelli, A. Ravenscroft, S. Holden,OREILLY.
COURSE PRE-REQUISITES:
Prerequisite: -NA
Corequisite: -NA
Additional material required in ESE: -NA
COURSE OBJECTIVES:
1 Exposure to develop programming skills.
2 To understand basic concepts of Python programming.
3 To develop confidence towards other programming languages.
COURSE OUTCOMES:
At the end of this course student should be able to learn
SNO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO1 2 2 2 - - - - 1 - 1 1 - -
CO2 2 2 2 - - - - 1 - 1 1 - - -
CO3 2 2 2 - - - - 1 - 1 1 - - -
CO4 2 2 2 - - -` - 1 - 1 1 - -
PO2 Discipline knowledge PO8 Individual and team work PSO2 ………………………….
PO3 Experiments and practice PO9 Communication
1 Python GUI
2 Tkinter concept to develop web pages
DELIVERY/INSTRUCTIONAL METHODOLOGIES:
ASSESSMENT METHODOLOGIES-DIRECT
ASSESSMENT METHODOLOGIES-INDIRECT
ASSESSMENT OF COURSE OUTCOMES (BY STUDENT FEEDBACK ON FACULTY
FEEDBACK, ONCE) (TWICE)
☐ ASSESSMENT OF MINI/MAJOR PROJECTS BY ☐ OTHERS
EXT. EXPERTS
Prepared by Approved by
(Ms. Kavita Dhiman) HOD
VISION:
Provide research-based and world-class computer education and training, and produce
ethically sound and technically competent versatile professionals.
MISSION:
Develop the ability to adapt to technological skills to fulfill the challenges of the ever-
evolving global world.
Induce knowledge that foster continuous improvement, self-learning, and innovation for
higher education.
Create a unique organizational value-based culture, professionalism in education, service,
and management and learner-centered education of excellence.
Prerequisite Course: NA
Teacher Centric Approach TC1: Chalk and Talk, TC2: PPT, TC3: Video Lectures etc. (Add
any other as per our NIT Poly)
Learner Centric Approach: LC1: Assignment, LC2: Mini project, LC3: Quiz, LC 4: Seminar
on recent trends LC5: Group Task etc. (Add any other as per our NIT Poly)
Course
Lecture Proposed Actual
Topics/Sub Topics Outcome Remarks
No. Date Date
Addressed
1 Computesum,subtraction,
multiplication,divisionandexponentof CO1 25-7-23
givenvariables input by the user.
2 Computeareaoffollowingshapes:circle,rectangle
CO1 28-7-23
,triangle,square,trapezoid andparallelogram.
3 Computevolumeoffollowing3Dshapes:cube
CO1 01-8-23
,cylinder,coneand sphere.
4 Compute and print roots of quadratic
equationax2+bx+c=0,wherethe valuesofa,b, CO1 04-8-23
andcareinputbythe user.
5 Print numbers upto Nwhicharenotdivisibleby
CO2 08-8-23
3,6,9,,e.g., 1, 2,4, 5, 7,….
6 Write a program to determine whether a triangle is
CO2 08-8-23
isoscelesornot?
7 Printmultiplication tableof anumberinputby the
CO2 11-8-23
user
8 Computesumofnaturalnumbersfromoneton
CO2 18-8-23
number.
9 PrintFibonacciseries upto nnumbers e.g.01 12358
CO2 22-8-23
13…..n
10 Computefactorialof agiven number. CO2 25-8-23
11 Countoccurrenceofadigit5inagivenintegern
CO2 29-8-23
umberinput by the user.
12 PrintGeometricand Harmonicmeansof
CO2 29-8-23
aseriesinputbythe user.
13 Evaluatethefollowingexpressions: CO3
x-x2 /2!+x3 /3!-x 4 /4!+…xn /n 01-9-23
b.!b. x-x 3/3!+x5 /5!-x 7/7!+… xn /n!
14 Printallpossiblecombinationsof4,5,and6. CO3 05-9-23
15 Determineprimenumberswithin aspecificrange. CO3 05-9-23
16 Count number of persons of age above 60 and CO3
08-9-23
below90
17 Computetransposeofa matrix. CO3 12-9-23
18 Performfollowingoperationsontwomatrices.1 CO3
15-9-23
)Addition2)Subtraction 3)Multiplication
19 Countoccurrenceofvowels CO3 22-9-23
20 Counttotalnumberofvowelsin aword. CO3 22-9-23
21 Determinewhetherastring ispalindromeornot. CO3 26-9-23
22 Perform following operations on a list of numbers: CO3
1)Insertanelement2)deleteanelement3)sortthelist4) 29-9-23
deleteentirelist
23 DisplaywordafterSortinginalphabeticalorder CO3 3-10-23
24 Performsequentialsearch onalistof givennumbers. CO3 6-10-23
25 Performsequentialsearchonorderedlistofgiven CO3
6-10-23
numbers.
26 Maintainpracticalnotebookaspertheirserial CO3
10-10-23
numbersinlibrary usingPythondictionary
27 Performfollowingoperationsondictionary1)Insert2) CO3
13-10-23
delete3) change
28 Checkwhetheranumberisinagivenrangeusingf CO3
17-10-23
unctions.
29 Write a Python function that accepts a string CO3
andcalculatesnumberofuppercaseletters 20-10-23
andlowercaselettersavailable in that string.
30 TofindtheMaxofthreenumbersusingfunctions. CO3 27-10-23
31 Multiplyall thenumbers inalistusing functions. CO3 31-10-23
32 SolvetheFibonaccisequenceusingrecursion. CO3 04-11-23
33 Get the factorial of a non-negative integer CO3
04-11-23
usingrecursion.
34 WriteaprogramtocreateamoduleoffactorialinPytho CO3
07-11-23
n.
35 Design a Python class named Rectangle, CO4
constructedby a length &width, also design a 10-11-23
method which willcomputethe areaofarectangle.
36 Design a Python class named Circle constructed CO4
by aradius and two methods which will compute 14-11-23
the areaandthe perimeter ofacircle.
37 DesignaPythonclasstoreverseastring‘wordby CO4
17-11-23
word’.
38 WriteaPythonprogram toreadanentiretextfile. CO5 21-11-23
39 DesignaPythonprogramtoreadfirstnlinesofatextfil CO5
24-11-23
e.
40 ConstructaPythonprogramtowriteandappendtextt CO5
28-11-23
oa fileand display thetext.
Prepared by Approved by
(Ms. Kavita Dhiman) (HOD)
Practical -1
1. Compute Sum, Subtraction, Multiplication, Division and Exponent of given
variables input by the user.
a=int(input("Enter first value:"))
b=int(input("Enter second value:"))
add=a+b
print("Addition:",add)
sub=a-b
print("Subtraction:",sub)
mul=a*b
print("Multiplication:", mul)
div=a/b
print("Division", div)
exp=a**b
print("Exponent:",exp)
OUTPUT:
Enter first value:20
Enter second value:10
Addition: 30
Subtraction: 10
Multiplication: 200
Division 2.0
Exponent: 10240000000000
Practical -2
2. Compute area of following shapes: circle, rectangle triangle, square,
trapezoid and parallelogram.
print("Find area of following Shapes")
print('''1. Circle
2. Rectangle
3. Triangle
4. Square
5. Trapezoid
6. Parallelogram''')
choice = int(input("Enter the choice:-"))
if choice == 1:
from math import pi
radius = float(input("Enter the radius of circle->"))
area = pi*radius*radius
print("Area of circle is:",area)
elif choice == 2:
length = int(input("Enter the length of the Rectangle:-"))
Breath = int(input("Enter the breath of the Rectangle:-"))
area = length*Breath
print("Area of Rectangle:-", area)
elif choice == 3:
base = int(input("Enter the base of the triangle:-"))
height = int(input("Enter the height of the triangle:-"))
area = 0.5*base*height
print("Area of triangle:-", area)
elif choice == 4:
side = int(input("Enter the side of square:-"))
area = side*side
print("Area of side of square:-", area)
elif choice == 5:
a = float(input("Enter the first base:-"))
b = float(input("Enter the second base:-"))
height = float(input("Enter the height:-"))
area = ((a+b)/2)*height
print("Area of trapezoid:-", area)
elif choice == 6:
base = int(input("Enter the base of the parallelogram:-"))
height = int(input("Enter the height of the parallelogram:-"))
area = base*height
print("Area of parallelogram:-", area)
else:
print("wrong input!!")
OUTPUT:
Find area of following Shapes
1. Circle
2. Rectangle
3. Triangle
4. Square
5. Trapezoid
6. Parallelogram
if choice == 1:
side = int(input("Enter the one side of cube:-"))
vol_cube = side**3
print("Volume of cube:-", vol_cube)
elif choice == 2:
from math import pi
radius = float(input("Enter the radius of cylinder->"))
height = float(input("Enter the height of cylinder->"))
vol_cylind = pi*radius*radius*height
print("Volume of cylinder is:",vol_cylind)
elif choice == 3:
from math import pi
radius = float(input("Enter the radius of cone->"))
height = float(input("Enter the height of cone->"))
vol_cone = 1/3*pi*radius*radius*height
print("Volume of cone:-", vol_cone)
elif choice == 4:
from math import pi
radius = float(input("Enter the radius of sphere->"))
vol_sphere = 4/3*pi*radius*radius*radius
print("Volume of sphere:-", vol_sphere)
else:
print("wrong input!!")
OUTPUT:
OUTPUT:
Enter a:1
Enter b:5
Enter c:6
the solution are (-5.5+0j) and (-4.5+0j)
Practical -5
5. Print numbers up to N which are not divisible by 3,6,9,, e.g. 1,2,4,5.
fori in range(lower,upper+1):
if((i%3!=0)&(i%6!=0)&(i%9!=0)):
print(i)
OUTPUT:
OUTPUT:
Enter the number:-6
fibonnaci series:-
0
1
1
2
3
5
Practical -10
10. Compute factorial of a given number
num=int(input("Enter a number:"))
Factorial =1
ifnum<0:
print("Sorry, factorial does not exist for negative number")
elifnum==1:
print("The factorial of 0 is 1")
else:
fori in range(1,num+1):
Factorial=Factorial*i
print("the factorial of", num,"is",Factorial)
OUTPUT:
Enter a number:8
the factorial of 8 is 40320
Practical -11
11. Count occurrence of a digit 5 in a given integer number input by the user
num=input("Enter Integer:")
d=input("Enter Digit:")
d=num.count(d)
Output:
Enter Integer:78547585335
Enter Digit:5
import math
def compute(a,b):
AM =(a+b)/2
print("Arithmatic mean=",AM)
GM= math.sqrt(a*b)
print("Geometric mean=",GM)
HM=(GM*GM)/AM
return HM
a=eval(input("enter the first number:"))
b=eval(input("enter the second number:"))
HM = compute(a, b)
print("Harmonic mean:",HM)
OUTPUT:
enter the first number:6
enter the second number:9
Arthmatic mean= 7.5
Geometric mean= 7.3484692283495345
Harmonic mean: 7.2
Practical -13
13. Evaluate the following expressions:
'''a. x-x2/2!+x3/3!- x4/4!+… xn/n!
b. x-x3/3!+x5/5!- x7/7!+… xn/n!'''
def fact(m):
if m==0:
return 1
else:
return m*fact(m-1)
s=0
x=int(input("Enter X :"))
n=int(input("Enter n:"))
fori in range(1,n+1):
s=s+((-1)**(i+1)*(x**i)/fact(i))
Output:
Enter X :2
Enter n:3
>
b)
def fact(m):
if m==0:
return 1
else:
return m*fact(m-1)
s=0
x=int(input("Enter X :"))
n=int(input("Enter n:"))
fori in range(1,n+1):
k=(2*i)-1
s=s+((-1)**(i+1)*(x**k)/fact(k))
Output:
Enter X :2
Enter n:3
>
Practical -14
14. Print all possible combinations of 4, 5, and 6.
fromitertools import combinations
for n in range(1,4):
A=combinations([a,b,c],n)
fori in A:
print(i)
OR
importitertools as IT
for n in range(1,4):
A=IT.combinations([a,b,c],n)
fori in A:
print(i)
Output:
Enter Ist Number:3
(3,)
(4,)
(5,)
(3, 4)
(3, 5)
(4, 5)
(3, 4, 5)
>
Practical-15
if m<n:
fori in range(m,n+1):
ifi>1:
for j in range(2,i):
ifi%j==0:
break
else:
print(i)
elif m>n:
fori in range(m,n,-1):
ifi>1:
for j in range(2,i):
ifi%j==0:
break
else:
print(i)
else:
OUTPUT:
Enter initial value:5
11
13
>
17
13
11
>
>
Practical-16
16.Count number of persons of age above 60 and below 90.
n=int(input("No. of Persons :"))
A=[]
fori in range(n):
A.append(int(input()))
print("Ages:")
fori in range(n):
if A[i]<=0:
print("NA")
elif A[i]>=110:
print("AGE?")
else:
print(A[i])
c=0
fori in A:
c=c+1
print(c)
OUTPUT:
No. of Persons :6
34
68
87
79
119
Ages:
34
NA
68
87
79
AGE?
>
PRACTICAL-17
17. Compute transpose of a matrix.
R=int(input("Enter Rows:"))
C=int(input("Enter Columns:"))
OUTPUT:
Enter Rows:
2
Enter Columns:
3
Enter Elements:
2
3
4
5
6
7
The Matrix is:
234
567
The Transpose of Matrix is:
25
36
47
PRACTICAL-18
18. Perform following operations on two matrices.1) Addition 2)
Subtraction 3) Multiplication
OUTPUT:
PRACTICAL-19
19. Count occurrence of vowels.
OUTPUT:
Enter any String
ILiveInIndia
Occurrence of Vowels in string
{'a': 1, 'e': 1, 'i': 5, 'o': 0, 'u': 0}
PRACTICAL:20
20. Count the total number of vowels in a word.
OUTPUT:
Enter any String
ILiveInIndia
Occurrence of Vowels in string:
{'a': 1, 'e': 1, 'i': 5, 'o': 0, 'u': 0}
Total No. of Vowels are:
7
PRACTICAL-21
21. Determine whether a string is palindrome or not.
OUTPUT:
Enter any String
madam
Entered String is: madam
Reverse of a string is: madam
Entered String is Palindrome
Practical-22
Perform following operations on a list of numbers:
1) Insert an element 2) delete an element 3) sort the list 4) delete entire
list
OUTPUT:
Enter how many elements you want in a list:
4
Enter 4 elements
Enter Element
23
Enter Element
67
Enter Element
45
Enter Element
12
LIST IS [23, 67, 45, 12]
Enter element to insert in a list:
87
Enter Index position at which u want to insert an element
2
List after inserting new element at index 2
[23, 67, 87, 45, 12]
Enter element you want to delete from list
67
List after deletion:
[23, 87, 45, 12]
Sorted list is:
[12, 23, 45, 87]
Deleting the entire list
[]
Practical-23
23. Display word after Sorting in alphabetical order.
OUTPUT:1
OUTPUT:2
Enter any String
welcome to python
Entered string is:
welcome to python
Sorted list is:
[' ', ' ', 'c', 'e', 'e', 'h', 'l', 'm', 'n', 'o', 'o', 'o', 'p', 't', 't', 'w', 'y']
String in Sorted form is:
ceehlmnooopttwy
PRACTICAL-24
24. Perform sequential search on a list of given numbers.
def FUN(LIST,key):
fori in range(len(LIST)):
if LIST[i]==key:
returni
break
return -1
LIST=[2,4,5,1,7,3]
print("The List is:",LIST)
key=int(input("The No. you want to search"))
n=FUN(LIST,key)
if n !=-1:
print(key,"is found at position ",n+1)
else:
print("Data not found")
Output:1
The List is: [2, 4, 5, 1, 7, 3]
The No. you want to search
4
4 is found at position 2
Output 2:
The List is: [2, 4, 5, 1, 7, 3]
The No. you want to search
8
Data not found
Practical -25
25. Perform sequential search on ordered list of given numbers.
defSequential_Search(list, item):
pos = 0
found = False
whilepos<len(list) and not found:
if list[pos] == item:
found = True
else:
pos = pos + 1
return found, pos
ele_list=[]
n=int(input("enter the number of elements:-"))
fori in range(0,n):
element=int(input())
ele_list.append(element)
item=int(input("enter the number to search:-"))
print("here is our list:-",ele_list)
print("here we are searching element present or not",Sequential_Search(ele_list,
item))
OUTPUT:
enter the number of elements:-5
2
3
4
5
6
enter the number to search:-3
here is our list:- [2, 3, 4, 5, 6]
here we are searching element present or not (True, 1)
Practical -26
26. Maintain practical note book as per their serial numbers in library using Python
dictionary
Practical -27
27. Perform following operations on dictionary 1) Insert 2) delete 3) change
Practical -28
28. Check whether a number is in a given range using functions
defcheck_range(n):
if n in range(10,20):
print( "Number",n,"is in the range")
else :
print("The number is outside the given range.")
n=int(input("enter number"))
check_range(n)
OUTPUT:
enter number15
Number 15 is in the range
Practical -29
29. Write a Python function that accepts a string and calculates number of upper
case letters and lower case letters available in that string.
defstring_test(s):
UPPER_CASE = 0
LOWER_CASE = 0
for c in s:
ifc.isupper():
UPPER_CASE += 1
elifc.islower ():
LOWER_CASE += 1
else:
pass
print ("No. of Uppercase characters : ", UPPER_CASE)
print ("No. of Lowercase characters : ", LOWER_CASE)
s = input ("Enter sentence :- ")
string_test(s)
OUTPUT:
Enter sentence :-PythonProgramminG
No. of Uppercase characters : 3
No. of Lowercase characters : 14
Practical -30
30. To find the Max of three numbers using functions.
Practical -31
31 Multiply all the numbers in a list using functions.
defmul_list(list) :
# Multiply elements one by one
product = 1
fori in list:
product = product * i
return product
list1 = [11, 12, 4, 3]
print(list1)
print("product: ")
print(mul_list(list1))
OUTPUT:
[11, 12, 4, 3]
product:
1584
Practical -32
32. Solve the Fibonacci sequence using recursion.
defrecur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
# check if the number of terms is valid
ifnterms<= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
fori in range(nterms):
print(recur_fibo(i))
OUTPUT:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Practical -33
33. Get the factorial of a non-negative integer using recursion.
defrecur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
ifnum< 0:
print("Sorry, factorial does not exist for negative numbers")
elifnum == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
OUTPUT:
The factorial of 7 is 5040
Practical -34
34. Write a program to create a module of factorial in Python.
Firstly, we have to create a module file name “factorial.py” same as python file extension.
OUTPUT:
Enter the number: -8
Practical -35
35. Design a Python class named Rectangle, constructed by a length &width,
also design a method which will compute the area of a rectangle.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
returnself.length * self.width
a = int(input("Enter the length: - "))
b = int(input("Enter the width: - "))
obj = Rectangle(a, b)
print("Area of rectangle is: ", obj.area())
OUTPUT:
Enter the length: - 40
Enter the width: - 30
Area of rectangle is: 1200
Practical -36
36 Design a Python class named Circle constructed by a radius and two methods
which will compute the area and the perimeter of a circle.
class Circle():
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
radius = int(input("Enter the radius: - "))
obj = Circle(radius)
print("Area of circle is: ", obj.area())
print("Perimeter of circle is: ", obj.perimeter())
OUTPUT:
Enter the radius: - 50
Area of circle is: 7850.0
Perimeter of circle is: 314.0
Practical -37
37. Design a Python class to reverse a string ‘word by word’.
classReverseString:
def __init__(self, string):
self.string = string
defreverse_string(self):
return " ".join(self.string.split()[::-1])
string = input("Enter a string: ")
reverse_string = ReverseString(string)
print("The result is: ", reverse_string.reverse_string())
OUTPUT:
Enter a string: word by word
The result is: word by word
Practical -38
38. Write a Python program to read an entire text file.
Firstly, we have to create a simple text file “sample.txt”: -
OUTPUT:
Practical -39
39. Design a Python program to read first n lines of a text file.
Firstly, we have to create a simple text file “sample.txt”: -
OUTPUT:
Practical -40
40. Construct a Python program to write and append text to a file and display
the Text
my_file = open("sample.txt", "w")
# here we have write in a file and we can write multiple lines
n = int(input("How many user name you can enter: - "))
fori in range(0, n):
user_name = input("Enter user name: - ")
user_age = input("Enter user classA: - ")
user_token = input("Enter user ClassB: - ")
my_file.write(user_name + "\n")
my_file.write(user_age + "\n")
my_file.write(user_token + "\n")
# herei am using apped method to append text in a file
my_file = open("sample.txt", "a")
append_text = input("Enter the text you want to append: - ")
my_file.write(append_text + "\n")
# herei am using read method to read text from a file
my_file = open("sample.txt", "r")
print("Here is the informatioin which we read from a file: -")
lines = my_file.read()
print(lines)
my_file.close()
OUTPUT:
How many user name you can enter: - 2
Enter user name: - python
Enter user classA: - BCA
Enter user ClassB: - Cyber
Enter user name: - python lab
Enter user classA: - BCA
Enter user ClassB: - Cyber
Enter the text you want to append: - All the best to all
Here is the informatioin which we read from a file: -
python lab
BCA
Cyber
All the best to all