0% found this document useful (0 votes)
13 views35 pages

Csc 201 Python Practical Manual22 PDF

Uploaded by

pjjwykbtrf
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)
13 views35 pages

Csc 201 Python Practical Manual22 PDF

Uploaded by

pjjwykbtrf
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
You are on page 1/ 35

KOLADAISIUNIVERSITY,IBADANFACUL

TYOFAPPLIEDSCIENCES
DEPARTMENTOFMATHEMATICALANDCOMPUTING

PYTHON
PROGRAMMINGLA
B MANUAL

NAME…………………………………………………………………………………………
MATRICNO:…………………………………………………………………………………
DEPARTMENT……………………………………………………………………………….
SESSION………………………………………………………………………………………
COURSECODE………………………………………………………………………………
COURSETITLE……………………………………………………………………………….
DEPARTMENTOFMATHEMATICALANDCOMPUTINGF
ACULTYOFAPPLIEDSCIENCES
INSTRUCTIONS
1. Studentsshouldreporttotheconcernedlabsasperthegiventimetable.
2. Studentsshouldmakeanentryin
thelogbookwhenevertheyenterthelabsduringpracticalorfortheirown personal work.
3. Whentheexperimentiscompleted,studentsshouldshutdownthecomputersandmakethecounterentr
yin thelogbook.
4. Anydamagetothelabcomputerswillbeviewedseriously.
5. Studentsshouldnotleavethelabwithoutconcernedfaculty’spermission.
6. WithoutPriorpermissiondonotenterintotheLaboratory
7. WhileenteringintotheLABstudentsshouldweartheir IDcards.
8. Studentsshouldsigninthe LOGINREGISTERbeforeenteringintothelaboratory
9. Studentsshouldmaintainsilenceinsidethe laboratory
10. Aftercompletingthe laboratoryexercise,makesuretoshutdownthe systemproperly
Week Topic Date of Date of Marks Remarks
Performance Checking (10)

GrandTotal
UNIT1

IntroductiontoPythonProgramming

Pythonisageneral-purposeinterpreted,interactive,object-oriented,andhigh-
levelprogramminglanguage. ItwascreatedbyGuidovanRossumduring1985-1990.
LikePerl,PythonsourcecodeisalsoavailableundertheGNUGeneralPublicLicense(GPL).Thisclassgi
vesenoughunderstandingon Pythonprogramminglanguage.

Prerequisites

YoushouldhaveabasicunderstandingofComputerProgrammingterminologies. A
basicunderstandingof anyof theprogramminglanguagesis aplus.

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python


isdesignedtobehighlyreadable.ItusesEnglishkeywordsfrequentlywhere
asotherlanguagesusepunctuation,and it hasfewer syntactical constructions thanother languages.

• Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
tocompile yourprogrambeforeexecutingit.ThisissimilartoPERLand PHP.

• Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreterdirectlyto writeyour programs.

• PythonisObject-Oriented−PythonsupportsObject-
Orientedstyleortechniqueofprogrammingthatencapsulatescodewithin objects.

• PythonisaBeginner'sLanguage−Pythonisagreatlanguageforthebeginner-levelprogrammersand
supports the development of a wide range of applications from simple text processing
toWWWbrowsers to games.

HistoryofPython

PythonwasdevelopedbyGuidovanRossuminthelateeightiesandearlyninetiesattheNationalResearch
Institute for Mathematics and Computer Science in the Netherlands. Python is derivedfrom many
other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unixshelland
otherscriptinglanguages.
Pythoniscopyrighted.LikePerl,PythonsourcecodeisnowavailableundertheGNUGeneralPublic
License(GPL).

Pythonisnowmaintainedbyacoredevelopmentteamattheinstitute,althoughGuidovanRossumstillhol
ds avital rolein directingitsprogress.

FeaturesofPython

• Easy-to-learn−Pythonhasfewkeywords,simplestructure,andaclearlydefinedsyntax.
Thisallowsthe student topick up thelanguagequickly.

• Easy-to-read−Pythoncodeismoreclearlydefinedandvisibletotheeyes.•Easy-to-maintain
−Python'ssourcecodeis fairlyeasy-to-maintain.

• Abroadstandardlibrary−Python'sbulkofthelibraryisveryportableandcross-platformcompatibleon
UNIX,Windows, andMacintosh.

• Interactive Mode − Python has support for an interactive mode which allows interactive
testinganddebuggingof snippetsof code.

• Portable−Pythoncanrunonawidevarietyofhardwareplatformsandhasthesameinterfaceonallplatfor
ms.

• Extendable−Youcanaddlow-
levelmodulestothePythoninterpreter.Thesemodulesenableprogrammersto add to or
customizetheirtoolstobemoreefficient.

• Databases−Pythonprovidesinterfacestoallmajorcommercialdatabases.

• GUI Programming − Python supports GUI applications that can be created and ported to
manysystem calls, libraries and windows systems, such as Windows MFC, Macintosh, and the
XWindow system of Unix. • Scalable − Python provides a better structure and support for
largeprogramsthan shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are
listedbelow

• ItsupportsfunctionalandstructuredprogrammingmethodsaswellasOOP.
• Itcanbeusedasascriptinglanguageorcanbecompiledtobyte-codeforbuildinglargeapplications.

• Itprovidesveryhigh-leveldynamicdatatypesandsupportsdynamictypechecking.

• Itsupportsautomaticgarbagecollection.

• Itcanbeeasilyintegrated withC,C++, COM,ActiveX,CORBA,and Java.

WritingtheFirstPythonProgram:

1. OpennotepadandtypefollowingprogramPrint(“HelloWorld”)

2. Saveaboveprogramwithname.py

3. Opencommandpromptandchangepathtopythonprogramlocation

4. Type“pythonname.py”(withoutquotes)toruntheprogram.

Example1:WriteaPythonprogramtoaskforusername, anddisplayhis/hername

asoutputname=input ('Enteryour name:')

print('Hello,',name)O

utput:

Enter your name:

KunleHello,Kunle

DataTypes
Python Data Types are used to define the type of a variable. It defines what type of data we
aregoing to store in a variable. The data stored in memory can be of many types. For example,
aperson's age is stored as a numeric value and his or her address is stored as
alphanumericcharacters.

Pythonhasvariousbuilt-indatatypeswhichwewilldiscusswithinthisclass:
• Numeric-int, float, complex
Examples
#This is integer data type (numeric)
x=3
type(x)
#This is float data type(numeric)
x=3
type(x+0.1)
#This is complex data type(numeric)
x=3
type(x+3j)
• String–str
#This is string data type
x= str(input("Enter your name "))
type(x)
#This is multiline string data type
multiline="""
I've been to your house dear, "Can i visit you later"
"""
print(multiline)
print(multiline[:4])
• Sequence-list,tuple,range
#This is sequence data type[list]. It can be modified
lists =[1,2,4,6,8,7]
lists1 =['banana','plaintain','guava','apple']
#nested list
lists2 =['banana','plaintain',3,['mango','orange'],'guava','apple',True]
#add to the list
lists2.append('cashew')
#change an index value
lists1[0]='pawpaw'
print(lists)
print(lists1[0])
print(lists2[3])
print(lists2[3][1])
#This is sequence data type[turple]. It cannot be changed
tuple1 =(1,2,4,6,8,7)
tuple2 =('banana','plaintain','guava','apple')
print(tuple1)
print(tuple2)
• Binary-bytes,bytearray, memoryview
#Byte is a sequence of immutable single bytes
byte1 = 'Hello Class'
arr=bytes(byte1,'utf-8')#It converts the message to a sequence of bytes
arr
#byte object
bytes.fromhex('FFFF F21E')

#Byte is a sequence of mutable single bytes. It has the same objects as byte
arr=bytearray(byte1,'utf-8')#It converts the message to a sequence of bytes
arr
# Memoryview allow acces to object internal data
my=memoryview(arr)
#It returns the ascii value
my[1]
list(my[1:3])
#It returns the message
my[1]=65
arr
• Mapping–dict
Example
#This is dictionary data type. It uses key not an index. We can update information with dictionary
#keyvalue pair
dict_list = {'name':'Adeyemi','level':200,'department':'computer science','favourite':['pounded
yam','icecream','meat pie']}
#dict_list.values()
#dict_list.keys()
#dict_list.items()
#print(dict_list )
dict_list['name']='Israel'
dict_list['name']
#We can also use the update command
dict_list.update({'name':'Christian','level':200,'department':'software engineering','favourite':['pounded
yam','icecream','meat pie']})
print(dict_list)
#we can also delete items
del dict_list['favourite']
print(dict_list)
• Boolean–bool
Example
#This is boolean data type
x=3>5
#type(x)
print(x)
• Set-set,frozenset
Example
#This is sequence data type[set]. It cannot have duplicate elements and cannot be acceseed with an index
set1 = {1,2,4,6,8,7,7 ,9,10,4,6}
set2 = {1,3,4,31,8,7,5 ,9,10,4,6}
print(set1)
print(set1|set2)
print(set1 & set2)
print(set1 - set2)
print(set1 ^ set2)
type(set1)
• None-NoneType

#None data type


my_name = None
print(my_name)
Assignment

1. Write a python program to request for the following information from student and
displaytheinformation asoutput. Name, MatricNo,Ageand Department

2. Writeapythonprogramtoacceptyourname andmatricnumberasinput andprintitout.


UNIT 2

PYTHONVARIABLES

Variablesarecontainersforstoringdatavalues.APythonvariableis areservedmemorylocationto store


values. In other words, a variable in a python program gives data to the computer forprocessing.

Every value in Python has a datatype. Different data types in Python are Numbers, List,
Tuple,Strings,Dictionary,etc.Variablescanbedeclaredbyanynameorevenalphabetslikea,aa,abc,etc
.

HowtoDeclareanduseaVariableLetseeanexample.Wewi

lldeclarevariable "a"andprintit.

a=100

print a

Variablenames
Therearejust a coupleofrulestofollowwhennamingyourvariables.
• Variablenamescancontainletters,numbers,and theunderscore.
• Variablenamescannotcontainspaces.
• Variablenamescannotstartwithanumber.
• CaseSensitive—forinstance,tempandTemparedifferent.

Example: To calculate temperature in

Fahrenheittemp = eval (input('Enter a temperature in

Celsius: '))print('InFahrenheit, thatis', 9/5*temp+32)

Lookingbackatourfirstprogram,weseetheuseofavariablecalledtemp.Oneofthemajorpurposesof
avariableisto remember avalue from onepart ofaprogramsothat
itcanbeusedinanotherpartoftheprogram. Inthecaseabove,thevariabletempstoresthevaluethatthe
user enters sothat wecan doacalculation with it in thenextline.
CreatingVariables

Pythonhasnocommand fordeclaringavariable.Avariableiscreatedthe
momentyoufirstassignavalue to it.

x=5
y =
"John"prin
t(x)print(
y)

ManyValuestoMultipleVariables

x, y, z = "Orange", "Banana",
"Cherry"print(x)
print(y)
print(z)

OneValuetoMultipleVariables
x = y = z =
"Orange"print(x)
print(y)
print(z)

OutputVariables
ThePythonprint()functionis oftenusedto outputvariables.

x = "Python is

awesome"print(x)

GlobalVariables

Variablesthatarecreatedoutsideofafunction(asinalloftheexamplesabove)areknownasglobalvariable
s.Globalvariablescanbeusedbyeveryone, bothinsideof functionsandoutside.

Example:Createavariableoutsideofafunction,anduseitinsidethefunction

x =

"awesome"defm

yfunc():

print("Pythonis" + x)
myfunc()Ex

ample2:

Createavariableinsideafunction,withthesamenameastheglobalvariable

x =

"awesome"defm

yfunc():

x =

"fantastic"print("Pytho

nis"+x)

myfunc()

print("Pythonis"+x)

Comment

Commentscanbeusedtoexplain Pythoncode.Comments
canbeusedtomakethecodemorereadable.Comments canbeusedto prevent executionwhen
testingcode.

#This is a
commentprint("Hello,Wo
rld!")

A
commentdoesnothavetobetextthatexplainsthecode,itcanalsobeusedtopreventPy
thonfromexecuting code.

MultilineComment

Python does not really have a syntax for multiline

comments.To add a multiline comment you could insert a #

for each line#Thisis acomment


#writtenin
#morethanjustonelinepr

int("Hello,World!")

Assignment

1. Asktheusertoenteranumber.Printoutthesquareofthenumber,butusethesepoptionalargumentt
o print itout in afull sentencethatendsin aperiod. Sampleoutputis shown
below.

Enter a number:
5Thesquareof5is25.

2. Write a program that asks the user for a weight in kilograms and converts it to
pounds.Thereare2.2 pounds in akilogram.
3. A lot of cell phones have tip calculators. Write one. Ask the user for the price of the
mealandthepercenttiptheywanttoleave.Thenprintboththetipamountandthetotalbillwiththe
tipincluded.
Unit3
ARITHMETICOPERATORS
Thearithmeticoperationsarethebasicmathematicaloperatorswhichareusedinourdailylife.Mainlyit
consists of seven operators.
i. Additionoperator-->'+'
ii. ii.Subtractionoperator-->'-'
iii. iii.Multiplicationoperator-->'*'
iv. iv.NormalDivisionoperator-->'/'
v. v.ModuloDivisionoperator-->'%'
vi. vi.FloorDivisionoperator--> '//'vii.Exponentialoperator(or)power operator--> '**'

i. AdditionOperator:Generally,additionoperatorisusedtoperformtheadditionoperationontwooperan
ds.Butinpythonwecanuseadditionoperatortoperformtheconcatenationofstrings,listsandsoon, but
operandsmustof samedatatype.
Example
x=2
y=3
print("ADDITIONRESUL

T:",x+y)output:ADDITIONRESULT:
5

SubtractionOperator
Generally,subtractionoperatorisusedtoperformthesubtractionoperationontwooperands

a=30
b =10
print ("Subtraction result : ",a-
b)output:Subtractionresult:20
Multiplicationoperator
• Generally,multiplicationoperatorisusedtoperformthemultiplicationoperationontwooperand
s.
• Butinpythonwecanusemultiplicationoperatortoperformtherepetitionofstrings,listsandsoon,
but operandsmustbelongto samedatatype.
num1 = 23
num2 = 35
print("MULTIPLICATIONRESULT:“,num1*num2)

FloorDivision
Suppose10.3isthere, whatisthe
floorvalueof10.3?Answeris 10
Whatistheceilvalueof10.3?An
sweris 11

RelationalOperators(or)ComparisonOperators
Followingarethe relational operatorsused inPython:
1. Lessthan(<)
2. LessthanorEqualto(<=)
3. Greaterthan(>)
4. Greaterthanor equalto(>=)
5. Equalto(==)
Assignment
1. Writeapythonprogramtoperformfourarithmeticoperations(multiplication,subtraction,divisi
onand addition) on two inputsaccepted from theconsole
2. Writeapythonprogramtosum fiveinputnumbersacceptedfromtheconsole.
UNIT4
PYTHONCONTROLSTRUCTURES
A program statement that causes a jump of control from one part of the program to another
iscalledcontrol structureorcontrol statement.

1. SequentialStatement
A sequential statement is composed of a sequence of statements which are executed one
afteranother. A code to print your name, address and phone number is an example of
sequentialstatement.
Example1
#Programto printyour nameand address -example forsequential statement
print("Hello!ThisisSeyi")
print("km18,Ibadanoyoexpressroad, koladaisiuniversity")
Output
Hello!ThisisSeyi
km18,Ibadanoyoexpressroad,koladaisiuniversity
2. AlternativeorBranchingStatement

In our day-to-day life we need to take various decisions and choose an alternate path to
achieveourgoal.Maybewewouldhavetakenanalternateroutetoreachourdestinationwhenwefindtheus
ual road by which we travel is blocked. This type of decision making is what we are to
learnthrough alternative or branching statement. Checking whether the given number is positive
ornegative,even or odd can all bedoneusingalternativeorbranchingstatement.

Pythonprovidesthefollowingtypesof alternative orbranchingstatements:


• Simpleifstatement
• if..elsestatement
• if..elifstatement

(i)Simpleifstatement
Simpleifis thesimplestof alldecision makingstatements.Condition shouldbe inthe
Syntax:
if<condition>:
statements-block1formofrelationalorlogicalexpression.
Example
#Programtochecktheageandprintwhethereligibleforvotingx=int(
input("Enteryourage:"))
ifx>=18:
print("Youareeligibleforvoting")

ii)if..elsestatement
Theif..else statementprovidescontroltocheckthetrueblockaswellasthefalseblock.Followingis
thesyntaxof ‘if..else’statement.
Syntax:
if
<condition>:state
ments-block 1else:
statements-block2

if…elsestatementexecution

if..elsestatementthusprovidestwopossibilitiesandtheconditiondetermineswhich BLOCKistobe
executed.

x=int (input("Enter your age :"))


if x>=18:
print ("You are eligible for voting")
else:
print("You are below 18")
(iii)Nestedif..elif...elsestatement:
Whenweneedtoconstruct achainofif statement(s)then‘elif’clause canbeusedinsteadof‘else’.
Syntax:
if <condition-
1>:statements-
block
1elif<condition-
2>:statements-
block2
In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-
block1 is executed, otherwise the control checks condition-2, if it is true statements-block2
isexecutedand even ifit failsstatements-block nmentioned inelsepartis executed.

else:

statements-blockn

If…elif..elsestatementexecution

‘elif’clausecombinesif..else-
if..elsestatementstooneif..elif…else.‘elif’canbeconsideredtobeabbreviation of ‘else if’. In an ‘if’
statement there is no limit of ‘elif’ clause that can be used, butan‘else’clauseif used should be
placedat theend.
Example:#ProgramtoillustratetheuseofnestedifstatementAver
age Grade
>=80andabove A
>=70and<80 B
>=60and<70 C
>=50and<60 D
Otherwise E
m1=int(input("Enter your score: "))
Enter mark in first subject : 34Entermarkinse if m1>=80:
print ("Grade : A")
elif m1>=70 and m1<80:
print ("Grade : B")
elif m1>=60 and m1<70:
print ("Grade : C")
elif m1>=50 and m1<60:
print ("Grade : D")
elif m1>=40 and m1<50:
print ("Grade : E")
else:
print ("Grade : F")
Output 1:
condsubject:78Grade: D
Output 2 :
Entermarkin firstsubject :67

Example:#Programto illustratetheuseof‘in’and‘notin’inif statement


ch=input(“Enteracharacter:”)#t
o checkif theletter isvowel
ifchin(‘a’,‘A’,‘e’,‘E’, ‘i’,‘I’,‘o’,‘O’,‘u’,‘U’):
print(ch,’ isavowel’)
#tocheckifthelettertypedis not‘a’or ‘b’or‘c’ ifchnot in(‘a’,’b’,’c’):print(ch,’
theletter is not a/b/c’)
Output 1:
Enteracharacter:ee
is a vowelOutput
2:
Enteracharacter:x
xthe letter isnot a/b/c

3. IterationorLoopingconstructs

Iteration or loop are used in situation when the user need to execute a block of code several
oftimes or till the condition is satisfied. A loop statement allows to execute a statement or group
ofstatementsmultipletimes.

Pythonprovidestwotypesofloopingconstructs:
(i) whileloop
(ii) forloop

(i) whileloop
The syntax of while loop in Python has the following
syntax:Syntax:
while<condition>:
statements block
1[else:
statementsblock2]
Inthe while loop,theconditionisanyvalidBooleanexpressionreturningTrueorFalse.The else part of
while is optional part of while. The statements block1 is kept executed till thecondition is True.
If the else part is written, it is executed when the condition is tested False.Recall while loop
belongs to entry check loop type, that is it is not executed even once if theconditionis tested False
in the beginning.

Example:programtoillustratethe useof whileloop-to printall numbersfrom10 to15

i=10 # intializing part of the control

variablewhile(i<=15):# testcondition

print (i,end='\t')# statements - block

1i=i+1 # Updation of the control

variableOutput:

10 11 12 13 14 15

Note:printcanhaveend,sepasparameters.endparametercanbeusedwhenweneedtogiveanyescape
sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sepas parameter can be used
tospecifyanyspecialcharacterslike,(comma);(semicolon)asseparatorbetweenvalues(Recalltheconc
eptwhichyouhavelearntin previouschapter abouttheformattingoptions inprint()).

Example:programto illustratethe use of whileloop-with else part


i=10 # intializing part of the control
variablewhile(i<=15):# testcondition
print (i,end='\t')# statements - block
1i=i+1 # Updation of the control
variableelse:
print("\nValueof iwhentheloop exit",i)
Output:1
10 11 12 13 14 15
(ii) for loop

for loop is the most comfortable loop. It is also an entry check loop. The condition is checked
inthebeginningandthebodyoftheloop(statements-block1)isexecutedifitisonlyTrueotherwisethe
loopis not executed.

Syntax:

forcounter_variableinsequence:

statements-block1

[else: # optional

blockstatements-block2]

Example:#programto illustratethe useofforloop-toprintsingledigit evennumber


foriinrange (2,10,2):
print(i,end='')
Output:
2468
Example:#programtoillustratetheuseofforloop-toprintsingledigitevennumberwithelse part
foriinrange(2,10,2):p
rint(i,end='')
else:
print("\nEnd ofthe loop")
Output:
2468
End ofthe loop

(iii) Nestedloopstructure
Aloopplacedwithinanotherloop iscalledasnestedloopstructure. Onecanplacea
whilewithinanotherwhile;forwithinanother for;forwithin while and whilewithin forto
constructsuchnested loops.
Following is an example to illustrate the use of for loop to print the following pattern
11 2
123
1234
12345
Example:programtoillustratetheusenestedloop-forwithinwhile
loopinn=int(input("Enter number: "))

#inn =6

i=1

while (i<=inn):

for j in range (1,inn):

print (j,end='\t')

if (j==i):

break

print (end='\n')

i =i+1
4. JumpStatements in Python

The jump statement in Python, is used to unconditionally transfer the control from one part of
theprogram to another. There are three keywords to achieve jump statements in Python :
break,continue,pass. Thefollowingflowchart illustratesthe useof break andcontinue.

(i) breakstatement

The break statement terminates the loop containing it. Control of the program flows to
thestatement immediatelyafterthe bodyof theloop.

A while or for loop will iterate till the condition is tested false, but one can even transfer
thecontrol out of the loop (terminate) with help of break statement. When the break statement
isexecuted, the control flow of the program comes out of the loop and starts executing the
segmentofcodeafter theloop structure.
Ifbreakstatementisinsideanestedloop(loopinsideanotherloop),breakwillterminatetheinnermostloop
.

Example

Programtoillustratetheuseofbreakstatementinsidefor
loopforword in “Jump Statement”:
ifword==“e”:br
eak
print(word,end='')O
utput:
JumpStat
UNIT5
DefiningPythonFunctions&Procedures
In generalprogramming,proceduresaresmall,dependentchunksofcodes
thatcanbeusedtoperformsomegiven tasks.Theobvious advantagesof usingproceduresinclude
 Reusabilityand elimination ofredundancy
 Modularityandenhanced proceduraldecomposition
 Maintenability
 Easyofintegration
 Readability
Therearetwotypesofprocedures;
 Functions
- pythonfunctionsareproceduresthat
containsomebodyofcodestoperformaparticular taskand returnavalue.
 Subroutines
These are more or less functions that perform a or some set of task (s) but do not return
avaluetothecallingprogram.Theyare also calledvoid functions.
Thegeneralstructureof apythonprocedureis shownbelow;
deffunction_name(listofparameters):st
atement1
statement2
……………
…statementN
 Takenoteofthefull colon (:)attheendofline1, itisusedtoinstructthecompiler thatthenext
setof instructions areto be taken asablock of codes.
 Also important is the indentation as shown in lines 2 to 5. The indentation is a way
oftelling the compiler that these statements are under the current block, function, or
evenloop.
Pythonprovidessomeout-of-the-box
functionsforperformingsomecommonprogrammingtaskscalled built-in functions.
Aswell,pythonallowsprogrammerstodefinetheirowncustomfunctions.Thesearecalled
user-
definedfunctions.Somecomm
onfunctionsare:
 typeconversionfunctions:int(),float(),str(),type(),bool()
Othersinclude:
 len(), chr(), min(), max(), range(), hex(), bin(), abs(), ord(), pow(), raw_input(),
sum(),format(),cmp(), dir(), oct(), round(), print()…etc.
Scoping
 Allpythonobjects,variable,orproceduresareexistsineitheroftwoscopes;localor
global.
 Argumentsorvariablesdeclaredinafunctionarealllocaltothatfunctionexceptotherwi
sedesignatedasglobal.
 Thelifeof alocalvariableis limited to theconfinesof thefunction ormodule it isin.
 However,variablesorobjectsdeclaredoutsideall functionsinaprogram
areglobaltoallproceduresin theprogram.
PythonLibraryFunctions
In Python, standard library functions are the built-in functions that can be used directly in
ourprogram.For example,
print() -prints thestringinsidethe quotation marks

sqrt() - returnsthesquarerootofanumber

pow() - returns the powerof anumber


These libraryfunctions aredefined insidethe module.And,to usethem
wemustincludethemoduleinsideour program.
Forexample, sqrt() isdefinedinsidethe math module.
BenefitsofusingFunctions
1. CodeReusable-
Wecanusethesamefunctionmultipletimesinourprogramwhichmakesourcodereusable.
2. CodeReadability-Functionshelpusbreakourcodeintochunksto
makeourprogramreadableand easyto understand.

Assignment
1. Writeapythonprogramusingafunctiontocomputethesumoftwonumbers.
2. Writeapythonprogram usingafunctiontocomputethefactorialofapositiveintegernumber

Assignment
Unit6

ProcessingStringData

Oftentimesinproblemsolvingwewouldwanttostoreorprocesstextualdatacontainingcharactersofthe
alphabets,numeralsandspecialcharacters.SuchdataarecalledStrings.

 Strings

These are collection of characters that are used to store and represent textual information.
Theycan be used to store anything data that will include letters or symbols such as your
name,address,department, coursecodeetc.

 Strings in python just like in many other programming languages are values placed
inbetweenapairofsingleordouble quotese.g.‘Ola’, “CSC202” etc.

 There are many operations that can be performed on strings, enumeration of


stringcharacters, concatenation, sorting, deleting characters, replacing, pattern
matching,reversingetc.

Inthememory,stringsinpythonareactuallystoredasanorderedsequenceofcharacters.Thefigurebel
owshowshowthestring“Science,Types”willbestored.
 So it can be seen that characters of a strings are actually stored in consecutive
memorylocations in memory where the first character occupies position or index 0 and
the secondindex 1 and to the last occupying index (N-1)where N is the length(total
number ofcharacters)ofthestring.Howeverfromtherear,theindicesiscountedfrom-1,-2to
–N!
 Noticethatevenspacesaretreatedlikeanormalcharacter.
StringLiterals
Stringliteralscanbewritten intwoformseither usingsingleordouble quotes.
 SingleQuote:
Name=‘KOLADAISI’
 DoubleQuote:
Name=“KOLADAISI”
Whicheveryouuse,beassuredpythontreatsthemequallyanditallowsyoutobeabletoembedonein
theother.
EscapeSequence
Thesearespecialcharactersembeddedinsidestringliteralstogivethemaspecialmeaningorintroducespe
cial charactersthat cannotbefoundon thekeyboard intothestring.
 The\canbeusedtoescapeanygivencharacterinordertooverallthedefaultbehaviourofthecharac
ter.
Forinstanceputtinganother‘withinapairof‘and‘flagsanerror,tovoidtheerror,wecanescapetheinner‘u
singthe\asshownbelow;
>>>place=‘Senate\’s Underground’
EscapeSequence
 Theycanalsobeusedtointroducespecialcharacterssuchasthefollowinginabodyofstring.
StringMethods
In memory, everything in python is actually treated as objects that can have methods,
andproperties.Whentreatedasobjects, stringsprovideasetof methods(functions)that
canbeusedtoperformso manybasic operations withstrings.Seetablebelowfor some ofthese;

Method Use

s.capitalize() Capitalizesfirstcharacter of s

s.count(sub) Countthenumberofoccurrenceof subin s

s.find(sub) Returnsthefirstsub ispresentin s

s.format(*fmt) Formatswiththelistofformatspecifiersfmt

s.index(sub) Returnsthefirstindexwheresuboccursins

s.endswith(sub) ReturnsTrueifsubendssandFalseotherwise

s.join(iterable) Usesstoconcatenatethe listofitemsin iterable

s.startswith(pre) ReturnsTrueifsubbeginssandFalseotherwise

s.lower() Convertsstolowercase string

Assignments

You might also like