0% found this document useful (0 votes)
9 views13 pages

Python Assignment (2nd Year, 3rd Sem)

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It is known for its simplicity, readability, and versatility, making it popular in various fields such as web development, data science, and artificial intelligence. Key features include being easy to learn, dynamically typed, and having extensive libraries and frameworks.

Uploaded by

anirbanbpcitcst1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views13 pages

Python Assignment (2nd Year, 3rd Sem)

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It is known for its simplicity, readability, and versatility, making it popular in various fields such as web development, data science, and artificial intelligence. Key features include being easy to learn, dynamically typed, and having extensive libraries and frameworks.

Uploaded by

anirbanbpcitcst1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

what is python 7 sorme features of pyfhon

Python is a
high-eveL,interpxeted, qeneral -poPose program
CYea ted by Guido van Ro ssum and frst
Langu
Yeleased in 1941. It is widely used because of its simplicty,
Yead abi lity, and versatity, ma King one f
the most popular
languages today in ieds Like eb develpment, dota seie
nce, arhficial Lntelligence,machine learining aomahen
and more.
Features of ython
i Simle and easy to learn.
i. Intey preted LonguagS

ivi cross - Platforrm


Extersive Librrles and Framewor ks

vi. Dynamically TYped.


vil.
High-level Langege
vii. Free and Sou rce
ix, Enbeddable and Extensi ble
X wide Appications.
environme
Jhat is development learnina
inter
nt2
An inte qrated beveloprnent Environrne
(IDE)isa
with
Softuare application that provics prog TameYS
teols to usritetest an d cde
fficienthy in
one place
Tnstead separate tools oy ediin
of using
an IDE com
s, complling ronning and debu
them into
gng
u ser- friendiylenvironment
bines

singe
Maln features f an b E

i <ode tditor
Compile/InterpYe ter.
Debuager
iv. Buid Automation Tools.
Project Management
vi. Ver sion ConteL Inte rahon
bifference betoeln .Teraethve Mode and script modo

Feture Interactive Mode Script Mode


Execuhon Line by ine whole Hle at Once

3se cae Ye0sa


Quick testing,learning Large
ble
programs,
code:
File needed NOe needed. RequiYes py Gle .

Output 3howS resut irnmed ShewS only final cutput


tely aftes execuHon
Speed

)
Slower for code.
g pregrams Faster foy Long

what is keyword ? Give example


A keyword is a YeseY ved ord in Py+hon ha hasa
special meaning and cannot be U sed as an ident
ey ((Lke < 2r2`ble name, 2ntor 7.03e, etc f
Py thon uses keyuoerd to define ts synta and
struc ture

Examples of ython keywoYd s


• i4, else,elif Osed foy Aecision na
while, for, breeak, continue used for lops.
def,Yeturn used fo fonctons
class, y, xcnPt, +ray ,
tth
True, Fase, None, end o, not.

what is tu ple?
data type in Python thot
At?re is aclletion
mutiple Hem s In ingle variable,
a
4 is
Can Store singe
Sim ilar to a ist, but the main diterence is !
Tuples are rnm u+eble 07ce eyeote -r eemets
Can not be changed, added OY remo ved.
features of Tupesi befned Usina Paren theses
1i.0Ydered ers have a ordeY,
ii. Lmmutable >Cannot modify afte creaon.
Alo ws dupi cates> can stese repeated valwes .
Can c2th 7 differen data typs>Nc3Ter s, Strings,e
what k ind of type conversion is performed by y thon interpreteY
and ho does it jvsti fies?
w

In ython, the interpete performs tuso main Kmds of type


conversion

)Impicit
-Also Called
Type Conversion (ype casting / Type Promotion)
Ty pe Pvomotion or Type 'Coercìon.
- Python automatically Converts one data type into another
wthot User invelvement,to prevert data Loss during
eatiens converte
A Here, a (int) is automateely
Exampl to fio at before additon.
a=5 because tloat has ider
This justt fies a

b= 2.5
Tange and pYecision than int, so Py thon
ÞYomotes int float to avod Loss f
Print (e) in for mation
print pe (<))
(ty

Ex phet Type convesion (Type [Link] User).


Like
Done manualy Using type Conversion functions
int (),float O,str O,et.
-Osed when you wcn to contol how dta is con ver
ted.
Example This iUstifes becauSe soetmts
automatie conver sion is not Safe (e.q,
string wont automatealy cone
Y =int (x) rt to integer),
print (yt5) has to expiei tty decide.
Porammer

Justification by Pythoni
)In arthmete, t converts
smaler data types inte
data types aveid data Loss intfoat
Larger
complex)
never con erts automatica ky f there is a

chance of Losing infermation


r ambi (e
"(23" wont Quto- Corvert to int)
string
mmeY's
lef+ to the vog> mme
Ki)Ex plet castng is left
decisin when ambiquty exists.
data type available in
ave ythnon G ive
thee basie-
ba sicr
Explain
an example.
) Nunerie Ty pesi
positive
int - integey numbers (wtole numbers,
neqathve).

print (a,type (o)).


numbers)
flo at e cimol numbers (real
DecimaL
b= 3414

(b,type (b))
pyint

•complex complex numbers (wth real


adpart)
ima ginany

print (<,type c)).

|
)
Boblean Type
Represents truth
tloq = Trc
print

Se
seqyen
Str
(string
values

(tlagtype (Glaq3)
Ce Typesi
tncl
TYue oY False.

Seqen ce chorac
+ers 'nSide
quotes

,
name =- "ytheon
print (name type (name))
collection (can change.
Li st ordered, mutable ene.

- numbers = 2,3,4 I
(numbers, type (numbers))
print
collecton (cannot
tople ordered, immutable eerent'
CotY ds= ((ojo,30)
cAange
print (ioords, type (coords))
i)Set ty pes i
Co letion
Set Mutable, wnorde red
Set , s(t,2,3,34)
frozen Irnmable >
print s, type
>fs = rozenset(li,2,3))
print (f s, type ts)).
.dict Rey value palrs
ae'
student -'name": " A ice ", i 204
-
pvint (student,ty pe
(student))
d foy ?
wha are the need uSed foy funetion
Afunchon is a block of reusa ble code that perfoms
specifie task. Instead of writing the same code
and n, he pu
again, +
insido a oncfi07 07d cal ht2 +
neede d.
Main Jsng functions -
needs| Advantage
Reusabilty
i> of Code
i)Modolarity.
i)Reada bility

iN) Avoids Repetion.


v) Te sting De bu 1jing Made Easy.
Co de Reusablidy Across Proqrams
vi)Abstraction
shat is wr4en stotement ?
the
stateement is an nstrucHon. that
In Python,
Can xehe
intreprefer Meeans Line f code
A Cr iten Staernent SimPly
that peror ms Some
Yten by te
PYeTammey
action.
Pes e Saements -
)Expvession statement
statement.
)Assimment
)conditional statement
statement .
FuncHon al Statement.
vi) Pass /Break/ continue State
et
what ore the ty pes
There
tour ty pes aYguros of0 n Python
)Positional Avqumemts
keywor d Arqumens
i) Default Arqumen ts.

ivariab le- lenqth Arquments

)befine Modle. file that ontains


A module in python is simply
Py thon code defni t ons fonches,
>
classes,
and Varib (es -that you can euse 'n hex proTo

-file exten sio n:


and
veusable,
- PurpOe ;To make
alnabe
cede
rqanized,
maint
12) what is Local vari able ? Give example .
variable that declayed
4 LoceL variable is ssed
only be acce
within
insjde functon and can
that functon.
ereated when tthe fncon storts exeuton

destroye
Cannot be
d ushen
0 he funcon
sI de 4he
end s
functon.
Example;
def my_functon ():
Print Tnside functon", X)
my.-func tionc )
Prin t "outsàe functhon :",)
OUtput

Inside functHon lo
N ame Error i name x s not defined.
write a ython pYogYam function ith umen ts
and with <etr )e .
def area --rectangle(lenqth ,wid th):
QYea
length * width
Yeturn are a
L= int
(input ("Enter length i ")
w-int (in put tr udth(Er i

tesult =area- Yectang le (,w)


print A rea iangle is:", vesut)
of rectangle

Oput+
Enter
Enter widthN 5
Area of rec tangle is 50
used with fonction
Explain four ty pes of ar qoments
with
Suitable
i Positional
example s
Araumets:
.
.Values are passed in the Sae orde rameters
as para are

deined
must match.
• The count ot argumerts
Example;
def student (name, ae):
prht (" Name: name)
print ("

Stude(Ai ce",2.0) .

i)keyword Ar quments = value fornat.


Parameters are passed using Keey

• rder doesnt matteY.


Example:
def student (name,aqe).
print CName ",nane)
print (Age:",age)
stu dent(age 22,
are - "Bob")
ii) Defaut Arguments ?
Some paramneters Can have defa t valwe. a

* 1f not provi ded, the defaut is used


defgreet hame, msg5 ="Helo");
print (msg name)
greet (“charlie)
., Good bye")
Teet (Dav:d
i
Variable - Length Arquments
iv) L

the exac t numbe of

Us d when we don't Hnow


advan ce.
arquments
Tuso typesi
vaviable aTs
non-kywoYd (stored stored
variable rquments
kwarqs > for keyword
as dictionary).

Example i

def add tnmbers):


to tal =
num brs!
total t n

print ("Sum", totaL)


add (2, 3,4)
add (G lo,15)
write the numby is Pyime
Program check if
not

nu3 int Cinp("Enter a number)


for in
Yange (2, num):
i

prin t (hum," is not a prime numbey"


breaIK
se
print (num,is a prime number ")
Hou do the contnch, brea and þass state
ment wor in Loo 2.
)byeak statement i

to e xit he
loop immediately, even it the
Condithon is sttu tr ue.
.The control qoes to the Hrst statement af4er he h

Contnue Sem2
O se d to skin the curYent eratn ct the loop.
.Control back to the next teration.

)Pass statemen;
.A null statemett does nothing
•Used as a statement is
place holder when
exe -
Syntacticaly required but y
CO te

ve preram find Fibonacci Sevies.


to
n =int input ("Entey the numbey of term si ")

b=
print (Fibonacci Seiesi")
for
Print
C= atb
a= b
b= C

Yam to fn d thhe SactoYioL of

number Ye cUY Sion.


def factorial (n)
n1:
Yeturn 1

lse :

num int (npct (


retun n* factoriaL (n-1)
Eoter a numbey to
1esult = factori al (rum)
nd Hs
factoriol

print (f- The facto,i al of {nu37 :s fvesu


DiffeYence between break and continue ?
Break Statement Conhnue statenent
Irmediately exis the lo0 ps| > S ps urren teratn
Conh cO -h the ne. <
Break s4atement Contnue Satent
Termi>aes hee loop comple i>Tc3ps. te he nu
tely. eraton (Loop Conti

Centrol goes outside


Outside he i)Control qoes
condihon
boack to

loop
Lep
want to skip
i)when yoU want to stor
stop i when
Cevain
you
cases but SH
looping early cornue.

vPytthon <br for i in range


(br) for i in range
)python
(,6): <br) if i-=3: <br) (1,6)<br)if i==3 <E)
Conti nue cbr print (i )(b)
break <br) print (() <br>
0utv;1,2, 4,5
0utputi 1,2

what IS bolean value?


Valwe isa data +ype hat vepresents one
A Boolean
of tuwo Possi ble states;
• True
False

Boblans are Used in


) condi ional Statemets
ii) Conmpari son eratons
LogicolL Oper ations
True False,
boo lean valwe in Aython is either
o
A
flou
mainly used for deeision-making and
contyL
in
Program S.
2 Expain Global and Local scope:

,
LocaL Scopei
declared inside function is locol
.A ariable a

to th 0+ f7 to.
It can ohly be accessed wthin that fonction
+ is Created when the function is called, and
destro yed wohen the fonction eds.
i) Global Scopei
,A vovioble declared 0cside ali fonctt07:,
global.
• It Can be accessed anywheye in he propom
the
(insde out side fnctions),

write Python program to accept tuso no,s mult

them and print the Nesu .


!)
ply

a int (input (" Enter first numbeY


b= int (input (' Enter second num beY )
- a*b
muitply
pyint (°Multipying numbes is-,mutiely)
both
two
wwrite
an
a+
d f
a
Python Proarm to aceept thie no.S
find the ove a test Qnd brint the Ye su
: .

b=
int(input
in

it(asb):

else:
print

Þrint
("
(input

Greatest

("
(Enter
("

GreatestNumber
Enter

Number
rst
Second

is ",
is
)
nomber

".b)
"))

the Chco'of tuo


write a
Proqram and find
numbers.
a= int (inpt (Eter number: )
b int Cinput Enter another numberi "))
i4 asb
Smaler b

se .
ma le = a

(1,smalley +1):
ifa%i and b o i =eO
-d=i s acd)
int The Gnco of faf and {b}
25) st ate the purpose f Teturn statement with
using
example ython statement.
funcion te!
The YetuYn statement is used in side a the
bac k to
)send a value (or mutiple values)
callod
plae ewhere he function Caas

immediately when eyecu


)Teminate Hhe fonction
ted
iAlouw the funcHon to be uSed as0ran expression
be Stoe used' in anoth
(So its resut
calculaton).
Valuee
Example 1rRetining o singe
def squarehum):

'
0c+p
retrnum num
Seyare is. 25
result SquaYe (5)
print Square is i resut)
Example 2i Returning ple vales
def cale (a,b):
return atb, a-b
Sum_val, diff val = cale (1o,4)
prlnt Sun" Sumval)
print fval)
("DifferenCe ;", diff.
0c+r,
Sum 14
Differencei 6.
Example 3;-Returnin ibithout Nalue:
def greet (ome):
I4 name" "

retuYn
Print("Helo,", name)
qreet ("Ai ce")
greet ().
what do you me an by vei ved and default argu
men be pas s
which ean at he tire f functon
Call ? Explain h
proam.
> RequNed Aqmenr
A(so Calle positionol otqument
d

The function must be called with all equired


Orqumnents,in the correct order.
you miss one, Pythor raises
Example i

def add (a,b):


teturn atb
prìnt (ad d (5, 3))
print (add (io))
)befaut Ar ment
defaut velue in the
• A poYameterCan have
funcon definition. is wsed.
.L no valve is passed, the default the defau It
OVerrides
value is passed,H
Ex ample:
def (rame, m
'Helo"):

Pint (ms nhme)'


greet CAi ce*).
et (Bob" " welCome")
Combined Example (Required t Defaut)
def studentdetails (name, course = <sE):
print Namei /nname)
py in t (" CouY Se
se:", course)
student_ detail s chandradip", "AI).
studentdetails ("Rahul")
Nam
CourSe: AL
: chA7drodlp Name ! Rahu|
CoUr Se ;

You might also like