0 ratings 0% found this document useful (0 votes) 37 views 34 pages Python Practical File
The document contains various Python programs demonstrating fundamental programming concepts such as printing messages, calculating areas and perimeters, determining even or odd numbers, finding the greatest of three numbers, and calculating factorials. It also includes programs for checking prime numbers, generating Fibonacci sequences, and identifying palindromes. Additionally, there are examples of string manipulation, matrix operations, and tuple handling, showcasing a wide range of Python functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Python Practical File For Later
Ln fesgramns. Le
\) Reuint (" Hello Wesilf |")
# Python Pregram Ae pound “Hello Wlevld |”
2)8 Batre pray aa ho print Orla of rectangle.
Le float (input (enter dength of steetungle : '))
b= Hoot [input O Order nba of setangls "'))
wouo= Leh
point (1 Apa Of steetarngle iss farta: 247")
@ pi [ Aswa a veclewgle = £1", donna (arte)
re programe a paint arta ama] pour
stadt = sank Linu Co Cnbex send” of uel?)
ose = 314 otal ee 2
petimeder = Q% 31% sed
print (* howe of Ustelr =" , int tora), Hl nodit=",
prin U’ Perimeter ol, Uso a poumeten)
“a Hyd program bo wlotah aum of 2 ruler _
numt = ¢ “Ouln \o enluas *)
ra a ne, ts ro ?
mt (nun) q Urine ee aan
bs on ae > tof aa st] a i722 |
4pornat (numt', um? , sum) ' J23
5) Cyne p ie
ae
bore = float linpak (* Auten Ane Asose of 4:"))
Anexakt = oat (input L bwdin A Asia of 4:"))
awa= oO 5¥ base ¥ het
te coleulath owe of suiglg
CEH preqan es Swap tse varwoblu.-
prukmunn = Ink input ( * Cuter mower 4 >‘)
purendaum = int Linpuk (4 des number, eu
punk" Balere duoapping, nuroes 1 = 1 diutnum,
* number 12 1) 42terrdnurn )
A aky An swap dwe (putea! umbrrg
m4) areevdaurn = AeA disek nun
print ( : Mba po umber 4= ! fienum, ‘number 2 ="
oy Aetendnum)
*)# Tle progam calauta, sceoh of, quadrats
ola
we rb + (EM
Do
¥a = lsat mput (* Onter wseffiuierd at")
b = deat (input (* Cxtter Ceefdcrem bt *))
o> bod Cina: “Ata Reet ae)
De bae> DARE
4 Deo:
o- (ob + 0) “ee O° 15) / (2*a)
soot =(-b- He 0-5)/ 2¥4)
pont (" toot 14", Hoots) a
to iz
>-b/2+a)
((-0) + 05)/ (2 a)
isp
ais
potind (“Root 3 Ae a
print (* Rost”, gaol Sa imapenary | Se)Number 32 is even.
---Program ends---
The Evenodd. py program determines whether the inputted number is even or odd. On ex-
ecution generates the following output in the shell window.
RESTART: D:/PYTHON/CHAP PROGRAMS/Chap 4/[Link] ="
Enter a given number = 32numi = int(input("Enter first number = "))
= = int(input("Enter second number = "))
= inti input("Enter third number = "))
The nestedif . py program determines the greatest of three numbers using nested “if state
ment. On execution generates the following output in the shell window.
sesscssss=== RESTART: D:/PYTHON/CHAP PROGRAMS/Chap 4/[Link] ============ —
Enter first number = 33
Enter second number = 43
Enter third number = 22
Number 43 is greatest
---Program ends---The grade. py program determines the grade of a student based on the marks obtained b
On execution generates the following output in the shell window.
ssascsssc=sss RESTART: D:/PYTHON/CHAP PROGRANS/Chap 4/[Link] ====s2=======>
nter total marks obtained (out of 108) = 75
Grade C
---Program ends---caf * (oegyarm ty prt and coheck viluthe, the LE
geen murnibes Lua by) axmabrong munnloet.
num = wt Linput C* Cuter a number § »)
YR — at oS -tta (num)
n= Len (num tr)
Axtal = um (int (digit) fox clige > rum_xtr)
UY Awe = = num?
punt (num, om a Pamnabrong number’)
ee : :
J petit (num , “da mo an emabvene, hnumbes. *)Learn Programming in Python
PROS
factor:
‘ial=1
number = int(input("Enter an integer: "))
‘The Factorial. py program on execution generates the following output in the shell
dow,
ESTART: D:/PYTHON/CHAP PROGRAMS/Chap 4/[Link]
Enter an integer: 6
Factorial = 720
In this program, we have used while loop to determine the factorial of a given number.
factorial of a number n is given by
factorial (n) = n x factorial (n - 1)
so we have choosen a while loop that will be executed as long as the number becomes
than 1 i.e. greater than 0. Each time loop executes, number is multiplied with one less number.
(on each pass, number is decremented by 1. This continues until number is greater than 0. On
the loop, the factorial of the inputted number is displayed.
‘The Prime. py program on execution generates the following output in the shell window.
seseszscssssns RESTART: D:/PYTHON/CHAP PROGRAMS/Chap 4/[Link] s=as==ssass===
Enter a number = 67
67. is Prime Nunber
In this program, we have used while loop to determine whether a given number is prime or
not. A prime number is divisible by 1 and itself. So a prime number always has two factors only, We
have used while loop (0 determine the number of factors of a given number and thus determineontro! Structures:
“Whether a given number is prime or not. =
num = int(input("Enter how many numbers in fibonaced:aerdas’, ;
isl
a=@ # First fibonacei number
b=1 # Second Fibonacci number
print("First ",num," Fibonacci. nuebers"):
"= RESTART: D:/PYTHON/CHAP PROGRAMS/Chap 4/[Link]
Enter how many numbers in fibonacci series: 5
First 5 Fibonacci numbers
e
In his program, we have used while loop to print first n fibonacci numbers. The n th fibonacci
umber is calculated using the formula,
fibonacci (n) = fibonacci (n - 2) + fibonacci (n - 1)
The first fibonacci number is 0 and the second fibonacci number is 1. To print first n fibonacci
nbers, we have used while loop with a condition i¢=num where 4 is the count that maintains how
any numbers have been printed so far, and it is incremented each time loop is executed. It is
ncremented, and the ith fibonacci number printed until it becomes equal to num which represents the
number.Learn Programming in Python
The hef. py program on execution generates the following output in the shell window.
== RESTART: D:\PYTHON\CHAP PROGRAMS \Chap 4\[Link] =========:
Enter first number = 10
Enter second number = 55
H.C.F of 1@ and 55 = 5
In this program, we have used while loop to compute and print hef of two inputted ni
‘We have used while loop with a condition ic=num1 or i<=num2 where i is the common factor of ty
numbers, and it is incremented each time loop is executed. This we can find all numbers from 1 t
maximum of two numbers that are divisible by both numbers. To check for divisibility we have use
ifcondition, if num1%:#4 Trograrn to gid LOM te, pute
i ink (input (° Urces foot nipbore’)
b= ink Linpatl® Gnles -ecend numbers ‘))
moximum = max (a, b)
while Tru?
“J Ganon so. == Sand (orion 38)?
punt eae of Es oF “ama! ie, cam)
boeak
maumum += 1mirot Structures if
print(num," is same as its reverse")
Ise? e ee
| 7 print(num,”" is not same as its reverse") sects
The palindrome. py program on execution generates the following output in the shell win-
dow
RESTART: D:/PYTHON/CHAP PROGRAMS/Chap 4/[Link] ======<==0=
Enter value of number = 1235
1235 is not same as its reverse
In this program, we have used while loop to check the number is same as its reverse.
“On first pass, sum = @ + (1235%19) = 5 numcopy = 1235 // 10 = 123
| (On second pass, sum = 5@ + (123%1@) = 53 numcopy = 123 // 10 = 12
"On third pass, sum = 53@ + (12%10) = 532 numcopy = 12 // 18@=1
| On fourth pass, sum = 5320 + (1%10) = 5321 numcopy = 1 // 18 = @—4
oe bo prdnit Herget Bua) Of eee
mum = int (input (Y Canter a numer § )
Laraestclint =0
: whi mums Dé
digdt = num 10
+4 disik > Lorgsk—digit ¢
2 Se
put (“The Largut digit im Are rumber i")
Dangeck. cigit )
13) 4 Pregvam to put seaverse of Giver numbos
rumn= tnt Linpud LY (utes a number 2)
sear —num = 0 ¥
while num > 0:
Mie = num), 10
stavtsge rum = (guveue—num + 10)
num = nun // 10
puint (* Roverded nurnbes, ALS) geuyerae nim)U4 Program to print att pis numbers 0
‘pheayoll. “
Jowwer. = tnt (input Gules Aho fewer Simit**))
unger = ink input U Guan Aha upper tims)
fe a some ( Lewer, uyper +4) 5 ;
Ud mms tt .
‘ Aon Xd gumnge. (4 num) 5
of sum], = = 08
pe
che & ad
phn|
I fucgvam to pid alt the Oalol umber amd |
em number waitin dt queen Songe.
Bower, = iat (input " nler Abe Lower Linat 2")
upper = amt (input Ut bantey Ahe upper Limit *))
print US Greer mumbeu jim the Womge £")
mum ian samge ( Aan, yer +4)
yy num$22=°5
pint (num , end =" As
privet 0) aaa
print (% det number in the Aouge t*) ;
fpr num en seomge (Lower , upper +2) 6
44 numt 2 | =O
itty Pt (num, wy et)
Be, Hf bnegvars to make a tumple cof [3
cep cobeattsr (V6 .
paint (* Simple Cobeulator )
print L* Select Opera”)
punt ("4 Aeldiém (+) *)
print (2. dubb weber (-) *)
ie" 4a Mult plication &)s)
pink ON: pinisisn YY) *)
Caree = input Cater cherie (4/2/13) 4)s
: is MA ae
4 cover “5
umt = (oak inpuk Ut Gules n
e ook US Gatun gee snuvnlasr 25)
eg :
parc 4" Srumt | 4 fren? = f nud + num2] )
z = ae 5 f £ .
oe Y 8 § mum th - 3 mum? J = f num — num?) ;
: ee SA i
mH put Lf" Jnumt}
. ) a suis
a) Bu mum) = i)
pot Tram J / {muna} = nent
»
elec $ : atte
Me 4 cated = } num ound’)
rareluc &
pout Ut In volial input *)
colewtoter, ()
post lenrolan
yeor = int (input (* nds year (eg. rs)e')
rnonth = tt (input L* Ginter menth (1-2):
print Ulm Herne sa the Cobenolor ’*)
pt ( colenolar. menth (yeor ) wer))
G33 %
be ;
n= iad Gnput (* Gules mumber of Shines =)
Apr 4 dw some (1, mn +4):
4" q Am Aowye Gg art)e
printf, end=**)
puut ()
hissDt Degen b prind thy foUlouring pilern ores. Lt
3
2
4 5 ee
+ 6am, 10
Count = 1
Luines = ink Uinput (" Cules ta munslonr of fava“)
fun i iw Aang (4, bine 4)§ dis
fu j 24 Aomnge (i |
3 ee oe wecw tl |
wee
plivk ( haut, al <*™)
sete a.
put )a Wythe program 2 print oe pattern.
*
ee
a
oe
+ et
sowd = juat (input (" Unter the umber of saw? ')
er £ ln panrge (1, stows + 1)5
pret (' (ope ee «(2xt-4)+" .
L gous ~ i)—
7 - [Link] - Program to count the number of wo! haracters, digits,
© characters, vowels and consonants in a string? sa }
9 tring=input("Enter string: ")
char=char+1
if(i-islower()==True):
-upper()
if([Link]()==True):
digit=digit+1
elif([Link]()==True) :
word=word+1
elif([Link]()==False):
sp=sp+1
elif(s in [At "eis Or Oe
vowel=vowel+4
else:
conso+=1 a
print("Number of characters in the string : ",char)
print("Number of words in the string : word)
print("Nunber of digits in the string : " digit)
Eee of special characters in the string : ",sp)
ee of vowels in the string : ",vowel)
lunber of consonants in the string : ",conso)
icount) , F
ntvowel . py program on execution generates the following output in the shell wi
indow.
ESTART: D:/PYTHON/CHAP PROGRAMS/Chap 7/countvowell. py ======="""~
Ente
ee Strang: Your password = 213@$7.
he Characters in the string : 22
words in the string : 4 .Learn Programming in Python
Number of digits in the string : 4
Number of special characters in the string: 3
Number of vowels in the string: 4
Number of consonants in the string: 8‘The matrixadd. py program on execution generates the following output,
RESTART: D:/PYTHON/CHAP PROGRAMS/Chap Lists/[Link] :
[[4, 4, 4], [9, 11, 9], [9, 13, 171]peint(C)
The matrixmul . py program on execution generates the following output,
= RESTART: D:\PYTHON\CHAP PROGRAMS\Chap Lists\[Link]
[5 12, 61] BeesProgram to
implement various
functions in a tuple.
subjects_tuple = ("Computer", "Maths", "English", 42,
5.6)
print("Tuple:", subjects_tuple)
print("First subject:", subjects_tuple[0])
print("Last element:", subjects_tuple[-1])
print("Slice from index 1 to 3:", subjects_tuple[1:4])
print("Tuple elements:")
for item in subjects_tuple:
print(item)
print("Number of elements:", len(subjects_tuple))
extra_tuple = ("Science", "History")
combined = subjects_tuple + extra_tuple
print("Combined tuple:", combined)Tuple: ('Computer', 'Maths', ‘English’,
42, 5.6)
First subject: Computer
Last element: 5.6
Slice from index 1 to 3: ('Maths',
‘English', 42)
Tuple elements:
Computer
Maths OU TPU T
English
2 p97! Tuple
Number of elements: 5
Combined tuple: ('Computer', ‘Maths',
‘English', 42, 5.6, ‘Science’,
"History')
== Code Execution Successful ===> |PRoaieiy [Link] - Program that inputs the elements of a |
© Gtudent roll number and its name using for loop and then display it?
n = int(input(‘Enter number of items = '))
mydict = dict() #empty dictionary
for ain range(n):
key = int(input(‘Enter the (key)roll | number: = 3) i
value = input( ‘Enter the (value) student name
print(* Eieeents of aieeionary are ',mydict)
The inputdict. py program on execution generates the following output,
RESTART: D:/PYTHON/CHAP PROGRAMS/Chap 8/[Link] ============
Enter number of items = 3
Enter the (key)roll number = 2120
Enter the (value)student name = Anurag
Enter the (key)roll number = 2125
Enter the (value)student name = Anshuman
Enter the (key)roll number = 2130
Enter the (value)student name = Vikram
Elements of dictionary are {2120: ‘Anurag’, 2125: ‘Anshuman", 2130: *vikram'}r
4
A
~> Lrogrannnt example). This xcanapl youl
how how iyehon Leaky on the
jm, He A allts of Loreal , Pru
voowable
J
wh tut ln ee
a yooviable nayned ‘pt t
H Nyon program to implement LEGb stofe suds
wenpoot math
p> SN 4p Gabel Scope
def puter () =
pis BIN15] + Evelering ope
de} imea ()
pi = sluisart 4 locat Jeope
pret Co Lent value” pl)
‘inne, ()
punt Us Onelourg velo + *, pl)
we)
| ovtruT
paint (8 Rutlt-in vole 2 *, rath «pt )
Jor a veriable
Loco vole’ [Link] \
esto, solace ata es eee
ng vilugs SANS
Gull values 3° (M4
}pROG 5.30 - Passbyobject.. py - Program that demonstrates the concept of passing immu-
ole object to a function?
# It doubles the values passed to it
def double(k)?
k-k*2 #reference of local varibale k
print (id(k))
print(*\t Inside a function, k = ",k)
g It calls the double() function
def main():
num = 5
print(id(num))#before modifying, reference of num
print("Before calling function, num = ",num)
double(num)
print("After calling function, num = ",num)
print (id(num) )#after modifying, reference of num
nain() # Function Call to main()
‘The Passbyobject . py program on execution generates the following output,
RESTART: D:\PYTHON\CHAP PROGRAMS\Chap Function\Passbyobject .py =:
1576560832
Before calling function, num = 5
1576560912
Inside a function, k = 10
After calling function, num = 5
1576560832ee
#® Python program to find the factorial of a number using recursion
er
fact = fact_rec(n)
print("Factorial of “,n," = ",fact)
‘The FactorialRecursion. py program on execution generates the following output,
==== RESTART: D:\PYTHON\CHAP PROGRAMS\Chap Function\FactorialRecursion.
er number whose factorial you want to calculate = 3.)
‘ialof 3 = 6
py ====
execution of the statement,
fact = fact_rec(n)
it first checks whether the Parameter value is
not @ as in our case it is 3, then it returns the
3. In this way, the recur_factorial
umber until n becomes 0. The Fig. 59
execution of the recursive calls starting with n=3, :
rec(3) = 3 * fact_rec(2) fact_rec(3) 2342 26! ei
- fact_rec(2 ae a“The ‘anonymous . py program on execution generates the filawia ante
= RESTART: D:\PYTHON\CHAP PROGRAMS\Chap Function\[Link] =:Python program to open a file and
display the contents of the particular file
# Open the file and write some contents
file = open(‘[Link]’, 'w')
[Link]("This is the first line.\n")
[Link]("This is the second line.\n")
[Link]()
# Read and display the file contents
file = open(‘[Link]’, 'r')
print("File contents after initial write:")
print([Link]())
[Link]()
# Append user-inputted data
user_data = input("Enter text to append to the file: ")
file = open(‘[Link]’, 'a’)
[Link](user_data + "\n")
[Link]()
# Read and display the updated file contents
file = open(‘[Link],, 'r')
print("File contents after append:")
print([Link]())
[Link]()Output
File contents after initial write:
This is the first line.
This is the second line.
Enter text to append to the file: Hello
World!
File contents after append:
This is the first line.
This is the second line.
Hello World!pp0G 9.28: Filecopy-Py- Program that copy contents of an existing file abc. txt fo another oor
"fie? : 9
v import 0s J
import syS
srcfilename = ‘abc. txt"
trgtfilename = "pqr. txt"
infile = open(srcfilename, 'r') #opens given file in read mode
if([Link]. isfile(trgtfilename)):
print(trgtfilename, ‘exists already’)
print(‘Contents overridden")
#[Link]() :
outfile = open(trgtfilename, 'w') #opens given file in read mode
for line in infile: eee
[Link](line) _
print('File ',srcfilename,
[Link]()
[Link]()
copier to xt gt lename)
The Fillecopy. py program on execution generates the following output in the shell window.
RESTART: D:\PYTHON\CHAP PROGRANS\Chap Files\[Link]
[Link] exists already
Contents overridden
File [Link] copied to [Link]