0% found this document useful (0 votes)
16 views94 pages

Unit 3 - Functions and Strings-1

This document covers the fundamentals of functions and strings in Python, including the need for functions, their definitions, variable scope, and the return statement. It also introduces modules, packages, and standard library modules, along with string operations, methods, and formatting. Additionally, it discusses good programming practices, documentation strings, and the use of lambda functions.

Uploaded by

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

Unit 3 - Functions and Strings-1

This document covers the fundamentals of functions and strings in Python, including the need for functions, their definitions, variable scope, and the return statement. It also introduces modules, packages, and standard library modules, along with string operations, methods, and formatting. Additionally, it discusses good programming practices, documentation strings, and the use of lambda functions.

Uploaded by

indalkarjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Unit 3

Functions and Strings


Syllabus :
• Need for functions
• Function: definition, call, variable scope and lifetime, the return statement.
• Defining functions
• Lambda or anonymous function
• documentation string
• good programming practices
• Introduction to modules
• Introduction to packages in Python
• Introduction to standard library modules.
• Strings and Operations:Concatenation,Appending,Multiplication and Slicing
• Strings are immutable
• Strings formatting Operator
• Built in string methods and functions
• Slice operation,ord(),chr() functions,in and not in operators
• Comparing strings,Iterating Strings,
• String Module
Need of Functions:
• Code reusability
• Dividing the program into separate well defined function- Simplify the process of program
development.
• Easy to understand, code, test
• Memory space is limited.
• They help program to be modular. Means they help in writing small parts of a program which are
meaningful.
• These small parts (modules) can be used again and again at different places in a program.
• Large program should follow DRY( Don’t Repeat Yourself) principle, bad programming is
WET(Write Everything Twice) or (We Enjoy Typing) principle.
Python has two types of functions.
1. Built in function. Ex- max(), min(),print()
2. User Defined Function
Ex- def f1():
print("welcome to function f1")
f1()
Definition of functions :
• A function is a block of organized and reusable program code that perform single, specific, and well defined
task.
• Python enables its programmer to break up a program into functions, each of which can be written more or
less independent of each others. Therefore, the code of one function is completely insulated from the codes
of the other function.
• A function f that uses another function g, is known as the calling function and g is known as the called
function.
• Note :Function name cannot contain spaces or special characters except underscore (–). Does not start with
numbers.
Syntax :
def function_name(parameters):
……
…….
return value
• Two keyword use to define function
1. def (compulsory)
2. return (optional)
Program : Write a program to add two numbers using a function :
Call to a function :
• A function can be called from any place in python script.
• Place or line of call of function should be after place or line of
declaration of function.
• Example: In add function code, add function is called on line 6.
• Add() function definition start on line 2 and ends on line 4.
• Then add() is called on line 6.
• function_name()- function call statement without parameter
• function_name(variable1, variable2)-function call statement with
parameter
Call to a Function
Variable Scope and Lifetime :
• Scope of variable- part of program in which a variable is accessible is called a scope.
• Lifetime of a variable- Duration for which the variable exists is called its lifetime.
• In functions, there are two kinds of variables, local and global.
Local Variables / Objects :
• The variable which are declared inside a function are called local variable.
• From outside of function we cannot access. Local variable is available to function
in which we declare it.
• Variables or objects which are used only within given function are local variables or
local objects.
• Local objects include parameters and any variable / object which is created in a
given function.
Variable Scope and Lifetime :
Ex-
def f1():
a=10 # local
print("a value is:",a)
def f2():
print("a value is:",a)# can not access
f1()
f2()
Global variables / objects :
• Objects which can be accessed throughout the script/program are global
variables or objects.
• Global variables or objects are created in python script outside any function.
• Global objects are available after “global” keyword defined in the script.
Ex-
a=20 # global
def f1():
print("a value is",a)
f1()
print("a value is",a)
Global variables / objects :
Global variable and local variable.
Ex-
num1=10 # global variable
print("global variable num1", num1)
def func(num2):
print("in function- local variable num2=", num2)
num3=30# local variable
print("in function local variable num3=", num3)
func(20)
print("num1 again", num1)
# print("num3 outside function =",num3) Error-
global keyword
• If local variable and global variable has same name then the function by default refers to the local
variable and ignores the global variable.
• If we want to access global variable inside a function we can access it by using global variable.
Ex-
a=10
def f1():
global a
a=20
print("a is",a)
def f2():
print("a is",a)
f1()
f2()
print("a is",a)
Return Statement :
• It is statement to return from a function to its previous function who
called this function.
• After return control goes out of the current function.
• All local variables which were allocated memory in current function will
be destroyed.
• Return statement is optional in python.
• Any function can return multiple arguments.
Return Statement :
Example
• return #This returns none value
• return None #This returns none value
• return a, b #This returns two values
• return a #This returns single value

• These all are valid examples of a return statement.


Return Statement Example:
• Ex Ex-
def f1(): def calculation(a,b):
print("Hello") add=a+b
return sub=a-b
print(f1())
mul=a*b
Ex-
div=a/b
def add(a,b):
return add, sub, mul, div
c=a+b
z=calculation(10,2)
return c
print(z)
z=add(10,20)
print(z)
Defining Functions
Syntax :
def function_name(parameters):
……
…….
return value
Arguments/ parameter to a Function :
• A function may accept arguments or it may not accept any
arguments or parameters.
• Arguments or Parameters to a function are treated as local
variable for that function.
• While defining the function, number of parameters has to
be specified as sequence of variables.
Types of Arguments :
There are different types of arguments :
• Required arguments
• Keyword Arguments
• Default Arguments
• Variable-length arguments
Required arguments
Required arguments or Positional Arguments
• The argument is passed to a function in correct positional order.
• These arguments are passed to function based on their position.
• Any normal arguments are positional arguments
• Number of argument in the function call should exactly match with the
number of arguments specified in the function definition.
Ex 1
def display(s):
print(s)
display("Hello")
Example of Required Arguments
Example of Required Arguments :
def f1(a,b):
c=a+b
return c
c=f1(10, 20)
print(c)
Keyword Arguments
Keyword Arguments
• These are another special category of arguments supported in python.
• Here arguments are passed in format “key=value” or name value
• Order is not important.
• number of argument is required.
Ex-
def display(name, age):
print("name:",name)
print("age:", age)
display(age=10,name="ABC")
Default Arguments
Default Arguments
• One of the argument to a function may have its default value.
• For example laptop has default built-in speakers. So if no speaker is
connected it will play default speaker.
• Similarly in function argument, a default value can be assigned to an
argument.
• Now if value for this argument is not passed by the user then
function will consider that arguments default value.
• Calling functions with very large number of arguments can be made
easy by default values
Example of Default Arguments :
Example of Default Arguments :
Ex
def mul(a,b=10):
c=a*b
return c
c=mul(5)
print(c)
Example of Default Arguments :
Variable length arguments
Variable length arguments
• Variable length argument is an argument that can accept any number
of values.
• Variable length arguments written with * symbol.
• It store all values in tuple.
Syntax
def function_name([arg1, arg2,….] * var_args_tuple):
function statement
return expression
Variable length arguments
def display(year, *subjects):
print("Year=",year)
print("Subjects=", subjects)
display("FE","PPS","M1","Eng. Chemistry","Eng, Physics")
-------------
o/p
Year= FE
Subjects= ('PPS', 'M1', 'Eng. Chemistry', 'Eng, Physics')
Ex- Variable length arguments

Ex- def ABC(*num):


print(num)
ABC(4,5,6)
• Ex-
def ABC(*num):
print(num[0])
print(num[1])
print(num[2])
ABC(4,5,6)
Lambda / Anonymous Functions :
• Lambda function not declare using def keyword, It is created by using
lambda keyword.
• Lambda function are throw away function, i.e. they are just needed where
they have been created and can be used anywhere a function is required.
• Lambda function have no name.
• We use lambda functions when we require a nameless function for
a short period of time.
• lambda function can take any number of arguments.
• Functions containing only single operation can be converted into an
anonymous function.
• ‘Lambda’ is the keyword used to create such anonymous functions.
Lambda / Anonymous Functions :
Syntax
lambda input arguments: expression
Example
#def add(a,b):
# c=a+b
# print(c)
#add(20,20)

z=lambda x,y: x+y


print(z(10,20))
Documentation String :
• In python, programmer can write a documentation for every
function.
• This documentation can be accessed by other functions.
Advantage of Document string
• It is useful when we want to know about any function in
python.
• Programmer can simply print the document string of that
function and can know what that function does.
Documentation String Example:
def f1():
"""This is f1 function.
This function print Hello world on
console"""
print("Hello world!!!")
print(f1.__doc__)
f1()
Documentation String Example:
• Ex- doc1.py • ABC.py
'''doc1 file for understanding string import doc1
documentation'''
print(dir(doc1))
print(help(doc1))
def add(a,b):
''' This is add function
It take two arguments a and b and
store result in c'''
c=a+b
print(c)
Good Programming practices
• Proper indentation.
• proper naming convention.
• Insert blank line to separate function and classes, and statements
blocks inside functions.
• Whenever required, used comment to explain the code.
• Use document strings that uses the purpose of the function.
• Write non repetitive code.
Introduction to Modules :
Module is a file with .py extension that has definitions of all
functions and variables that we use in other program

• Modules make python programs re-usable.


• Every python code (.py) file can be treated as a module.
• A module can be accessed in other module using import
statement.
• A single module can have multiple functions or classes.
• Each function or class can be accessed separately in import
statement.
Introduction to Modules :
Example to create your own module
• Create a file named sample.py in your directory.
• Write function add() in it. (as we have seen in previous
sections)
• Now create another file trial.py in same directory
• In trial.py write
• import sample.add
print(“addition is “, sample.add(10,20))
• Now run trial.py.
• Now the output will be 30.
Introduction to Modules :
Ex- Sample.py Ex- a1.py
import Sample
def add(a,b): Sample.add(10,20)
c=a+b Sample.mul(10,20)
print("Addition is",c) Ex- a2.py
from Sample import add,mul
def mul(a,b): add(3,3)
c=a*b mul(3,3)
print("Multipication",c) Ex- a3.py
from Sample import *
add(10,5) add(1,2)
mul(10,2) mul(2,2)
Introduction to Modules :
• __pycache__ is a directory that contains bytecode cache files that are
automatically generated by python.
Ex-
from math import pi,sqrt
print("PI=",pi)
print("square_root=",sqrt(9))
Packages in python
• A packages is a hierarchical file directory structure that has modules and other packages within it.
• Package is nothing but folders/directory.
• In our computer systems, we store our files in organized hierarchies. We don’t store them all in
one location. Likewise, when our programs grow, we divide it into packages.
• In real-life projects, programs are much larger than what we deal with in our journey of learning
Python. A package lets us hold similar modules in one place.
• Like a directory may contain subdirectories and files, a package may contain sub-packages and
modules.
• Packages are collections of modules and packages.
• Package can contain sub packages.
Packages in python
Packages in python
• Creating package:
- Package is folder/directory it contain __init__.py file.
- __init__.py file can be empty, it indicates that the directory it contains is a
Python package, so it is imported the same way a module can be imported.
- pyc file is created by the Python interpreter when a *. py file is
imported into any other python file. The *. pyc file contains the
“compiled bytecode” of the imported module/program so that the
“translation” from source code to bytecode can be skipped on
subsequent imports of the *. py file.
Packages in python
• Ex-
Package (Folder)
SubPackage (SubFolder)
FirstModule.py (Module)
def f1():
print(“I am in first Module/ program”)
SecondModule.py (Module)
def f2():
print(“I am in second module/ program”)
Sample.py (Module)
from SubPackage import FirstModule, SecondModule
FirstModule.f1()
SecondModule.f2()
Standard Libraries in Python :
• Modules that are preinstalled in Python are together known as standard library.
• Some useful module in standard library are string, re, datetime, random, os,
multiprocessing, subprocess, socket, email, json, doctest, unittest, argparse, sys.
• We can use this modules for performing task like string parsing, data serialization, testing,
debugging, and manipulating dates, emails, command line arguments etc.
1. Math (import math)
• This is a package for providing various functionalities regarding mathematical operations.
• Method- import math
dir(math)- written names without any docs
help(math)- It provide documentation
2. Random (import random)
• This is the module which supports various functions for generation
of random numbers and setting seed of random number generator.
Standard Libraries in Python :
Strings :
• The python string data type is a sequence made up of one or more
individual characters, where a character could be a letter, digit,
whitespace, or any other symbols.
• String is continues series of characters delimited by single, double
quotes. triple single quotes, triple double quotes.
• There is a built-in class ‘str’ for handling Python string. You can
prove this with the type() function.
• E.g.- name=‘India’, name=“India“, name=""“India""“.
name='‘’India'''
Strings:
mystr=“TCS : This is my class."

str="Welcome to my class"

print(mystr)
print(str)

Output :
TCS : This is my class.
Welcome to my class
Strings :
String Accessing
• We can access each individual character of a string by using
index.
• Each character can be accessed in two ways - from the front, or
from the rear end.
• Left to right- Forward index (Positive index)
• Right to left- Backward index (Negative index)
Strings:
mystr="PYTHON"

print("The First character is :",mystr[0])


print("The Third character from :",mystr[-3])

Output :

The First character is : P


The Third character from : H
Escape Sequence or a Back-slash:
• escape sequence or a back-slash will inform the compiler to
simply print whatever you type and not try to compile it.
• You must use one escape sequence for one character. For
example, in order to print 5 double quotes, we will have to use
5 backslashes, one before each quote.
• Python also supports the \n – linefeed and \t – tab sequences.
• EX- Q="what's your name?“- Valid
Q='what's your name?’- Invalid
Q='What\'s your name?’ -Valid
Strings:
print("Five double quotes", "\"\"\"\"\"")
print("Five Single quotes", "\'\'\'\'\'")

Output:
String Concatenation :
• The word concatenate means to join together.
• Concatenation is the operation of joining two strings together.
• Python Strings can join using the concatenation operator +.
str="Python"
str1="Programming"
str2="!!"

print(str)
print(str1)
print(str2)

str3=str+" "+str1+".."+str2
print(str3)
Python
Programming
!!
Python Programming..!!
String appending:
• Append means to add something at the end. In python you can add one
string at the end of another string using the += operator.
• "Concatenate" joins two specific items together, whereas "append"
adds another string to existing string.
• Ex- s="Py"
s=s+"thon“ or s+="thon“
• Ex.
str="hello:"
name=input("Enter name")
str+=name
print(str)
Multiplication or Repetition :
• To write the same text multiple times, multiplication or
repetition is used.
• Multiplication can be done using operator *.
str= "My Class is Best..."
print(str*3)

Output :
My Class is Best…
My Class is Best…
My Class is Best…
String Slicing :
• A substring of a string is called slice.
• Slicing is a string operation.
• Slicing is used to extract a part of any string based on a start index
and end index.
• The extracted portions of Python strings called substrings.
• In slicing colon : is used. An integer value will appear on either
side of colon.
• You can take subset of string from the original string by using []
operators also known as slicing operators.
String Slicing :
Syntax :
string_name[starting_index : finishing_index : character_iterate]
• String_name is the name of the variable holding the string.
• starting_index is the index of the beginning character which you want in your
sub-string.
• finishing_index is one more than the index of the last character that you want
in your substring.
• character_iterate is how many characters to extract in each jump.
str="Python Programming is very interesting"

print("Characters from 3rd to 6 :",str[2:6])


print("Characters from 1st to 6 :",str[0:6])
print("Characters from 8th onwards :",str[7:])
print("Characters from 1st onwards :",str[0:])
print("Last two Characters :",str[-2:])
print("Characters from Fourth Last onwards :",str[-4:])
print("Characters from Fourth Last to Second Last :",str[-4:-3])
print("Last two Characters :",str[-11:])
print("Reversing Characters of a string :",str[::-1])
print("Alternate Characters from 1st to 18th :",str[0:17:2])
Output :

Characters from 3rd to 6 : thon


Characters from 1st to 6 : Python
Characters from 8th onwards : Programming is very interesting
Characters from 1st onwards : Python Programming is very
interesting Last two
Characters : ng Characters from Fourth Last onwards : ting
Characters from Fourth Last to Second Last : ti Last two
Characters : interesting Alternate
Characters from 1st to 18 : Pto rgamn
Strings are immutable
• Immutable- Non Changeable.
• Whenever you try to modify an existing string variable, a new string
is created.
• EX
s="Python"
id(s)
2375308936240
s="Java"
id(s)
2375312788528
String Formatting
• String formatting is the process of infusing(fill) things in the string
dynamically and presenting the string.
• Formatting with % Operator.
• Formatting with format() string method.
• Formatting with string literals, called f-strings.
• Formatting with String Template Class
String Formatting Operator
• Formatting with % Operator.
• % sign, this string formatting operator is one of the exciting feature in Python.
• The format operator, % allows user to construct strings, replacing parts of strings with the
data stored in variables.
• The syntax for the string formatting operator is.
"<Format>" %(<Values>)
Ex-
name= "ABC"
age= 8
print("Name=%s and Age=%d"%(name, age))
print("Name=%s and Age=%d"%('xyz', 10))
String Formatting
String Formatting
1. a=‘j’ 6. A=100000
print("a value % c"%a) print("%e"%A)🡪 1.000000e+05
2. a=10 7. pi=3
b=20 print("%f"%pi) 🡪 3.000000
print("a value is %d"%a) 8. pi=3.14
print("a value is %i"%a) print("%f"%pi) 🡪3.140000
3. name="abc" 9. 3.140000
print("Name is %s"%name) print("%g"%a) 🡪 3.14
4. a=32768 10. a=10.100000
print("%u"%a) print("%G"%a)🡪10.1
5. a=10 11. 10.1
print("%o"%a)🡪12 a=1.000000e+05
print("%x"%a)🡪a print("%G"%a)🡪100000
print("%X"%a)🡪A
String Formatting
• To use two or more argument specifiers, use a tuple
(parentheses):
Ex-
name="abc"
age=20
address="xyz, pin 424201“
print("%s\n%d\n%s"%(name, age, address))
String Formatters:
• Sometimes, you may want to print variables along with a string.
• You can either use commas, or use string formatters for the
same.
• Ex-
name=input("Enter your name :")
city= "Pune"
country="India"
print("I am",name, "from",city,"\n""I love",country)
String Formatters : Format() method
• The Format() formats the specified values and insert them inside the string
placeholder. The placeholder define using curly bracket {}.
• It has the variables as arguments separated by commas. In the string, use curly
braces to position the variables.
Ex- print("Welcome to {}".format("Python"))
Ex-s1="Hello"
s2="How are you?“
print("Hiii {} {}".format(s1,s2))
print("Hiii {0} {1}".format(s1,s2))
print("Hiii {1} {0}".format(s1,s2))
print("Hiii {}".format(s1,s2))
print("{s2} {s1} How are you?".format(s1="Hii",s2="Hello"))
print("I Like {0}.{1}".format("Python Programming", "Its very interesting"))
print("value of a and b is {a},{b}".format(a=30,b=40))
Formatted String using F-strings

• To create an f-string, prefix the string with the letter “ f ”. The string
itself can be formatted in much the same way that you would with
str.format(). F-strings provide a concise and convenient way to embed
python expressions inside string literals for formatting.
• Ex-
name="abc"
print(f"My name is {name}")
String Formatters : Template
• This class is used to create a string template for simpler string
substitutions.
Ex-
from string import Template
str=Template('My name is $name and I am from $city studying in $college
College')
str1=str.substitute(name='ABC', city='Pune', college='SKNCOE’)
print(str1)

String Methods and Functions :
• Python provides us with a number of functions that we can
apply on strings or to create strings.
capitalize() :
• This function capitalizes first letter of string.
str ="python programming"
print(str)
print(str.capitalize())
len() :
• The len() function returns the length of a string
str="Python Programming“
print(len(str))
String Methods and Functions :
lower() and upper() :
• These methods return the string in lowercase and uppercase,
respectively.
Ex- str="pYthOn proGramMinG"
print(str.upper())
print(str.lower())
islower() :
• The method islower() return true if the Python string contains
only lower cased character(s) otherwise return false
String Methods and Functions :
isupper() :
• The method isupper() return true if the Python string contains only
upper cased character(s) otherwise return false.
str="pYthOn proGramMinG"
str1="python programming"
str2="PYTHON PROGRAMMING"
print(str.islower())
print(str1.islower())
print(str2.isupper())
String Methods and Functions :
strip() :
• It removes blank spaces from the beginning and end of the
string.
str=" Python Programming "
print(str)
print(str.strip())
String Methods and Functions :
isdigit() :
• Returns True if all characters in a string are digits.
str="Python Programming"
str1="123456789"
print(str.isdigit())
print(str1.isdigit())
String Methods and Functions :
isalpha() :
• Returns True if all characters in a string are characters from an
alphabet.
str ="PythonProgramming"
str1="Python 123456789"
print(str.isalpha())
print(str1.isalpha())
String Methods and Functions :
isspace() :
• Returns True if all characters in a string are spaces.
str =" "
str1="Python 123456789"
print(str.isspace())
print(str1.isspace())
String Methods and Functions :
isalnum() :
• The method isalnum() is used to determine whether the Python
string consists of alphanumeric characters.

str ="Python Programming"


str1="Python123456789"

print(str.isalnum())
print(str1.isalnum())
String Methods and Functions :
istitle() :
• The method istitle() return true if the string is a title cased.

str ="python programming"


str1 ="Python programming"
str2 ="Python Programming"

print(str.istitle())
print(str1.istitle())
print(str2.istitle())
String Methods and Functions :
title() :
• The method title() returns a copy of the string in which first
character of all words of string are capitalized.
String Methods and Functions :
swapcase() :
• The method swapcase() returns a copy of the string in which all
case based character swap their case.
String Methods and Functions :
startswith() :
• It takes a string as an argument, and returns True if the string it is applied
on starts with the string in the argument.
chr(number)
chr(number)

ord() and chr() Functions


• The ord() function returns the ASCII code of the character.
• The chr() function returns character represented by a ASCII number.
• ASCII- A to Z(65-90), a to z(97-122), 0 to 9(48-57)
• ord(character)

EX-
ch='a'
print(ord(ch))
o/p- 97
Ex-
print(chr(97))
o/p- a
in and not in Operators/ Membership
Operator
• in and not in operator can be used • Ex-
with string to determine whether a
a="Welcome to python“
string is present in another string.
• Ex- 'b' in 'apple’ if "to" in a:
🡪 False print("Found")
• Ex- 'b' not in 'apple’
else:
🡪 True
• Ex- Ex- 'a' in ‘a’
print("Not Found")
🡪True 🡪 Found
• Ex- Python' in 'Python’
🡪 True
Comparing String
• Python allows you to compare strings using relational(or comparison)
operators such as >, < , <=, >= etc.
Iterating string
• String is sequence type(Sequence of character), You can iterate through the string using for loop.
• The for loop executes for every character in str. The loop starts with the first character and
automatically ends when the last character is accessed.
EX-
s="Welcome to Python"
for element in s:
print(element,end="")
Ex-
s="Welcome to python"
for i in range(len(s)):
print(s[i])
Ex-
s="Welcome to python"
for i,ele in enumerate(s):
print(i, ele)
Iterating string
• Iterate string using while loop:
Ex-
s="Welcome to Python"
index=0
while index<len(s):
char=(s[index])
print(char,end='')
index=index+1
The String Module
• The String Module Consist of a number of useful constants, classes,
and functions.
• These function are used to manipulate a string.
• import string
• dir(string)
['Formatter', 'Template', '_ChainMap', '__all__', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re',
'_sentinel_dict', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase',
'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation',
'whitespace’]
The String Module
• To Know details of particular items.
type(string.digits)
<class 'str’>
• import string
• string.digits
'0123456789’
• import string
string.__builtins__.__doc__

You might also like