Unit 2 Functions Strings
Unit 2 Functions Strings
! Output:-
My string
! Example 2:-
! def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
! printinfo( age = 50, name = "miki" )
! Output:-
Name: miki
Age 50
Default Arguments
! A default argument is an argument that assumes a default value
if a value is not provided in the function call for that argument.
! Example:-
! def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
! printinfo( age = 50, name = "miki" ) Output:-
! printinfo( name = "miki" ) Name: miki
Age 50
Name: miki
Age 35
Variable-Length Arguements
! You may need to process a function for more arguments than
you specified while defining the function.
! These arguments are called variable-length arguments and are
not named in the function definition, unlike required and
default arguments.
! Syntax:-
! def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
! An asterisk (*) is placed before the variable name that
holds the values of all non keyword variable arguments.
! This tuple remains empty if no additional arguments are
specified during the function call.
! Example:-
! def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
print(“For Loop:”)
for var in vartuple:
print (var)
return Output is:
! printinfo( 10 ) 10
Output is:
! printinfo( 70, 60, “Hello” )
70
For Loop:
60
Hello
! Example:-
! def printinfo( arg1,arg2, *vartuple,**keyword ):
"This prints a variable passed arguments"
print (arg1)
print (arg2)
print (vartuple)
print (keyword)
return
! printinfo( 10 )
! printinfo( 10, 20 )
! printinfo(10, 20, 30, 40, 50, a = 60, b = 70)
! Output:-
! TypeError: printinfo() missing 1 required positional argument:
'arg2’
! Output:-
! 10
! 20
! ()
! {}
! Output:-
! 10
! 20
! (30, 40, 50)
! {‘a’:60, ‘b’:70}
Anonymous Functions
! You can use the lambda keyword to create small anonymous
functions.
! An anonymous function is a function that is defined without a name
! anonymous functions are defined using the lambda keyword.
! Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
! An anonymous function cannot be a direct call to print because lambda
requires an expression.
! Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
! Although it appears that lambdas are a one-line version of a function, they
are not equivalent to inline statements in C or C++, whose purpose is to
stack allocation by passing function, during invocation for performance
reasons.
! Syntax:-
Output:-
Value of total: 30
Value of total: 40
map(), filter() and reduce()
! The map(), filter() and reduce() functions bring a bit of functional
programming to Python.
! Thesyntax is:
! map(function, iterable(s))
The map() Function
def start_with_A(s):
return (s[0] == ‘A')
fruits = ['Apple','Banana','Pear','Apricot']
map_object = map(start_with_A,fruits)
print(list(map_object))
The map() Function
Output:
[True, False, False, True]
!
The map() Function
def calculatesquare(n):
return n*n
num = (1,2,3,4)
result = map(calculatesquare,num)
print(set(result))
Num = (1,2,3,4)
Result = map(lambda n: n*n, Num)
print(set(Result))
The map() Function
! Output:
! {16, 1, 4, 9}
The map() Function and lambda
#map with lambda
fruits = ['Apple','Banana','Pear','Apricot']
map_object = map(lambda s: s[0]=='A',fruits)
print(list(map_object))
fruits = [‘Apple','Banana','Pear','Apricot']
map_object = map(start_with_A,fruits)
print(list(map_object))
The map() Function and lambda
Output:
[True, False, False, True]
The filter() Function
! Similar to map(), filter() takes a function object and an
iterable and creates a new list.
! As the name suggests, filter() forms a new list that contains
only elements that satisfy a certain condition, i.e.
the function we passed returns True.
! The syntax is:
! filter(function, iterable(s))
The filter() Function
def start_with_A(s):
return s[0] == 'A'
fruits = ['Apple','Banana','Pear','Apricot']
filter_object = filter(start_with_A,fruits)
print(list(filter_object))
The filter() Function
! Output:
['Apple', 'Apricot']
The filter() Function
# random list
random_list = [1, 'a', 0, False, True, '0']
! Also,
in Python 3 reduce() isn't a built-in function anymore,
and it can be found in the functools module.
The reduce() Function
! reduce() works by calling the function we passed for the
first two items in the sequence. The result returned by
the function is used in another call to function alongside
with the next (third in this case), element.
The reduce() Function
The reduce() Function
Python Global, Local and Nonlocal variables
In Python, a variable declared outside of the function or in global scope is known as
a global variable. This means that a global variable can be accessed inside or
outside of the function.
• Example#1
def foo():
print("X inside:",x)
foo()
print("X Outside:”,x)
Python Global, Local and Nonlocal variables
X inside: global
X Outside: global
! Example#2
#Global local variable demo
x = "global"
def foo():
x = x * 2
print("X inside:",x)
foo()
print("X outside:",x)
Python Global, Local and Nonlocal variables
Traceback (most recent call last):
File "Func.py", line 166, in <module>
foo()
File "Func.py", line 164, in foo
x = x * 2
UnboundLocalError: local variable 'x' referenced before assignment
Python Global, Local and Nonlocal variables
#Global local variable demo
x = "global"
def foo():
x = "Local"
x = x * 2
print("X inside:",x)
foo()
print("X outside:”,x)
Output:
X inside: LocalLocal
X outside: global
Python Global, Local and Nonlocal variables
Local Variables
A variable declared inside the function's body or in the local scope is
known as a local variable.
Output:
inner: nonlocal
outer: nonlocal
Recursive Function
! In Python, we know that a function can call other functions.
It is even possible for the function to call itself. These types of
construct are termed as recursive functions.
! The following image shows the working of a recursive
function called recurse.
Recursive Function
! The factorial of 3 is 6
Type Conversion
! Python defines type conversion functions to directly
convert one data type to another.
! int(a,base) : This function converts any data type to
integer. ‘Base’ specifies the base in which string is if data
type is string.
! float() : This function is used to convert any data type to a
floating point number
!s = int(input(),2)
! c = int(s,2)
! print ("After converting to integer base 2 : ", end="")
! print (c)
! e = float(s)
! print ("After converting to float : ", end="")
! print (e)
Output:-
After converting to integer base 2 : 18
After converting to float : 10010.0
! ord() : This function is used to convert a character to
integer.
Output:-
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
! dict(): This function is used to convert a tuple of order
(key,value) into a dictionary.
count = 0
for letter in 'Hello World':
if(letter == ‘l'):
count += 1
print('%d letters found' %count)
Escape Sequence
He said, “What’s up?”
! Ifwe want to print a text like - He said, "What's there?"- we
can neither use single quote or double quotes. This will
result into SyntaxError as the text itself contains both single
and double quotes.
>>> print("He said, "What's up?"")
File "<stdin>", line 1
print("He said, "What's up?"")
^
SyntaxError: invalid syntax
>>> print("He said, "What's up?'")
File "<stdin>", line 1
print("He said, "What's up?'")
^
SyntaxError: invalid syntax
Escape Sequence
>>> print('''He said, "What's there?"''')
He said, "What's there?"
>>> print('He said,"What\'s there?"')
He said,"What's there?"
>>> print("He said,\"What's there?\"")
He said,"What's there?"
Escape characters
Escape characters
>>> print("C:\\Python32\\Lib")
C:\Python32\Lib
>>> print("This is printed\nin two lines")
This is printed
in two lines
>>> print("This is \x48\x45\x58 representation")
This is HEX representation
String special operators
! Assume string variable a holds 'Hello' and variable b holds
'Python', then −
print("This is \x61 \ngood example!!")
print(r"This is \x61 \ngood example!!”)
! Output:
This is a
good example!!
This is \x61 \ngood example!!
! Ifwe want to concatenate strings in different lines, we can
use parentheses.
>>> s = ('Hello'
... 'World!')
>>> print(s)
HelloWorld!
The format() Method for Formatting Strings
! The format() method that is available with the string object is
very versatile and powerful in formatting strings.
! Format strings contains curly braces {} as placeholders.
! We can use positional arguments or keyword arguments to
specify the order.
The format() Method for Formatting Strings
#default (implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n---Default Order---')
print(default_order)
#keyword arguments
print("Hello {name}, your balance is
{blc:9.4f}".format(name="Adam",blc=230.2346))
The format() Method for Formatting Strings
! Output
Hello Adam, your balance is 230.234600
Hello Adam, your balance is 230.234600
Hello Adam, your balance is 230.2346
Hello Adam, your balance is 230.2346
Hello Adam, your balance is 230.2346
The format() Method for Formatting Strings
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc:5.6f}.".format("Adam",
blc=230.2346))
The format() Method for Formatting Strings
! Output
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.234600.
Numbers formatting with format()
# integer arguments
print("The number is:{:d}".format(123))
# float arguments
print("The float number is:{:f}".format(123.4567898))
# octal, binary and hexadecimal format
print("bin: {0:b}, oct: {0:o}, hex: {0:x}”.format(12))
Output:
The number is:123
The float number is:123.456790
bin: 1100, oct: 14, hex: c
Numbers formatting with format()
# integer numbers with minimum width
print("{:5d}".format(12))
# width doesn't work for numbers longer than padding
print("{:2d}".format(1234))
# padding for float numbers
print("{:8.3f}".format(12.2346))
# integer numbers with minimum width filled with zeros
print("{:05d}".format(12))
# padding for float numbers filled with zeros
print(“{:08.3f}".format(12.2346))
Output:
12
1234
12.235
00012
0012.235
Numbers formatting with alignment
Type Meaning
Output:
12
12.235
12000
- 12.235
# string padding with left alignment
print("{:<5}".format("cat"))
# string padding with right alignment
print("{:>5}".format("cat"))
# string padding with center alignment
print("{:^5}".format("cat"))
# string padding with center alignment
# and '*' padding character
print(“{:*^5}".format("cat"))
Output:
cat
cat
cat
*cat*
Truncating strings with format()
# truncating strings to 3 letters
print("{:.3}".format("caterpillar"))
# truncating strings to 3 letters
# and padding
print("{:<5.3}".format("caterpillar"))
# truncating strings to 3 letters,
# padding and center alignment
print(“{:^5.3}".format("caterpillar"))
Output:
cat
cat
cat
String Formatting Operator
! One of Python's coolest features is the string format operator
%. This operator is unique to strings and makes up for the
pack of having functions from C's printf() family. Following is
a simple example −
! Ex:
print("My name is %s and weight is %d kg!" % ('Zara', 21))
! Output:
My name is Zara and weight is 21 kg!
! Ex:
print("My name is %s and weight is %d kg!" % ('Zara', 21))
print("The character is %c” %'Z')
print("My value is %i " %1.0)
print("My value is %e " %10)
print("My value is %f" %10)
! Output:
My name is Zara and weight is 21 kg!
The character is Z
My value is 1
My value is 1.000000e+01
My value is 10.000000
Methods of String Objects
! capitalize(): Capitalises first letter of string
! Ex:
str = "hello world"
print("str.capitalize() : ", str.capitalize())
! Output:
('str.capitalize() : ', 'Hello world’)
! center(width, fillchar): Returns a space-padded string with
the original string centered to a total of width columns.
Padding is done using the specified fillchar. Default filler is a
space.
Methods of String Objects
str = "hello!"
print("str.center() : ",str.center(10,'a'))
print("str.center() : ",str.center(10))
str="Hello"
print("str.center() : “,str.center(10,'a'))
Output:
('str.center() : ', 'aahello!aa')
('str.center() : ', ' hello! ')
('str.center() : ', 'aaHelloaaa')
Methods of String Objects
! count(str, beg= 0,end=len(string)): Counts how many times
str occurs in string or in a substring of string if starting index
beg and ending index end are given.
str = "Hello\tworld!!"
print("Original String: ",str)
print("Original String: ",str.expandtabs())
print("Original String: ",str.expandtabs(8))
print("Original String: “,str.expandtabs(16))
Methods of String Objects
! expandtabs(tabsize=8): Expands tabs in string to multiple
spaces; defaults to 8 spaces per tab if tabsize not provided.
! Output:
Original String: Hello world!!
Original String: Hello world!!
Original String: Hello world!!
Original String: Hello world!!
Methods of String Objects
! find(str,beg=0 end=len(string)): Determine if str occurs in
string or in a substring of string if starting index beg and
ending index end are given returns index if found and -1
otherwise.
print("rindex: ",str1.rindex(str2))
print("index: ",str1.index(str2))
print("rindex: ",str1.rindex(str2,0,10))
print("index: ",str1.index(str2,10,len(str1)))
Methods of String Objects
! Output:
rindex: 15
index: 15
Traceback (most recent call last):
File "Strings.py", line 217, in <module>
print("rindex: ",str1.rindex(str2,0,10))
ValueError: substring not found
!
Methods of String Objects
! isalnum():Returns true if string has at least 1 character and
all characters are alphanumeric and false otherwise.
str = "Thisis2021"
print(str.isalnum())
str1 = "This is string example....hello!!!"
print(str1.isalnum())
Output:
True
False
Methods of String Objects
! isalpha(): returns True if all the characters are alphabet
letters (a-z).
! Example of characters that are not alphabet letters:
(space)!#%&? etc.
str = "Thisis2021"
print(str.isalpha())
str1 = "This is string example....hello!!!"
print(str1.isalpha())
str2 = "hello"
print(str2.isalpha())
Methods of String Objects
! isdigit():
Returns true if string contains only digits and false
otherwise.
str3 = "hello"
print(str3.isdigit())
str4 = "1234"
print(str4.isdigit())
Methods of String Objects
! islower(): This method returns true if all cased characters in the
string are lowercase and there is at least one cased
character, false otherwise.
! isspace(): Returns true if string contains only whitespace
characters and false otherwise.
! istitle(): The method istitle() checks whether all the case-based
characters in the string following non-casebased letters are
uppercase and all other case-based characters are
lowercase
! isupper(): The method isupper() checks whether all the case-
based characters (letters) of the string are uppercase.
Methods of String Objects
str1 = "This is string example....hello!!!"
print("Lower: ",str1.islower())
str1 = "this is string example....hello!!!"
print("Lower: ",str1.islower())
print("Space: ",str1.isspace())
str1 = " "
print("Space: ",str1.isspace())
str1 = "this is string example....hello!!!"
print("Title: ",str1.istitle())
str1 = "This Is String Example....Hello!!!"
print("Title: ",str1.istitle())
str1 = "This Is String Example....Hello!!!"
print("Upper: ",str1.isupper())
str1 = "THIS IS STRING EXAMPLE...HELLO!!!"
print("Upper: ",str1.isupper())
Methods of String Objects
! Output:
Lower: False
Lower: True
Space: False
Space: True
Title: False
Title: True
Upper: False
Upper: True
Methods of String Objects
! join(seq):The method join() returns a string in which the
string elements of sequence have been joined
by str separator.
Output:
Joint : a-b-c
Lenth : 34
Methods of String Objects
! lstrip():The method lstrip() returns a copy of the string in
which all chars have been stripped from the beginning of
the string (default whitespace characters).
! rstrip()
The method rstrip() returns a copy of the string in which
all chars have been stripped from the end of the string
(default whitespace characters).
Methods of String Objects
str = "88888888888This is string example....hello!!!88888888888"
print("Left Strip: ",str.lstrip('8'))
print("Right Strip: “,str.rstrip(‘8'))
print("Strip: ",str.strip('8'))
Output:
Left Strip: This is string example....hello!!!88888888888
Right Strip: 88888888888This is string example….hello!!!
Strip: This is string example....hello!!!
Methods of String Objects
! max(str): The method max() returns the max alphabetical
character from the string str.
! min(str): The method min() returns the min alphabetical
character from the string str.
str = "This is string example....hello!!!"
print("Strip: ",str.lstrip())
print("Max String: ",max(str))
print("Min String: “,min(str))
Output:
Max String: x
Min String:
Methods of String Objects
! replace(old, new [, max]): The method replace() returns a copy
of the string in which the occurrences of old have been replaced
with new, optionally restricting . the number of replacements
to max.
str = "This is string example....hello!!!This is really a string"
print("After replacement: ",str.replace("is","was"))
print("After replacement: “,str.replace("is","was",3))
Output:
After replacement: Thwas was string example....hello!!!Thwas was really
a string
After replacement: Thwas was string example....hello!!!Thwas is really a
string
Methods of String Objects
! ljust(width[, fillchar]): The method ljust() returns the string left
justified in a string of length width. Padding is done using the
specified fillchar (default is a space). The original string is
returned if width is less than len(s).
! rjust(width,[, fillchar]): The method rjust() returns the string
right justified in a string of lengthwidth. Padding is done using
the specified fillchar (default is a space). The original string is
returned if width is less than len(s).
Methods of String Objects
str1 = "This is string example....hello!!!"
print("Right justified: ",str1.rjust(50,'0'))
print("left justified: “,str1.ljust(50,'0'))
Output:
Right justified: 0000000000000000This is string example....hello!!!
left justified: This is string example….hello!!!0000000000000000
Methods of String Objects
! startswith(str,
beg=0,end=len(string)): Determines if string or a
substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and
false otherwise.
str = "This is string example....hello!!!"
prefix = "This"
str_pre = str.startswith(prefix)
print(str_pre)
str_pre = str.startswith(prefix,0)
print(str_pre)
str_pre = str.startswith("is",4,9)
print(str_pre)
Methods of String Objects
! startswith(str,
beg=0,end=len(string)): Determines if string or a
substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and
false otherwise.
True
True
False
Methods of String Objects
! swapcase(): Inverts case for all letters in string.
Output:
tHIS IS STRING EXAMPLE....hELLO!!!
this is string example....hello!!!
Methods of String Objects
! title():The method title() returns a copy of the string in which
first characters of all the words are capitalised.
Output:
This Is String Example....Hello!!!
this is string example....hello!!!
THIS IS STRING EXAMPLE....HELLO!!!
Methods of String Objects
! zfill(width): The method zfill() pads string on the left with
zeros to fill width.
! split(): The method split() returns a list of all the words in the
string, using str as the separator (splits on all whitespace if
left unspecified), optionally limiting the number of splits
to num.
Methods of String Objects
str = "This is string example....Hello!!!"
print(str.zfill(40))
print(str.split())
print(str.split(' ‘,2))
Output:
000000This is string example....Hello!!!
['This', 'is', 'string', 'example....Hello!!!']
['This', 'is', 'string example....Hello!!!']
Methods of String Objects
! Python does not handle uppercase and lowercase letters the
same way that people do. All the uppercase letters come
before all the lowercase letters.
word = ‘Pineapple'
if word == 'banana':
print("All right, bananas")
if word < 'banana':
print('Your word,'+word+',comes before banana')
elif word > 'banana':
print('Your word,'+word+',comes after banana')
else:
print("All right, bananas")
Methods of String Objects
! Python does not handle uppercase and lowercase letters
the same way that people do. All the uppercase letters
come before all the lowercase letters.
! Output:
Your word,Pineapple,comes before banana
Functional
Approach in
Python
! Functional programming is all about
expressions. We may say that the
Functional programming is an expression
oriented programming.
! Expression oriented functions of Python
provides are:
lambda
map(aFunction, aSequence)
filter(aFunction, aSequence)
reduce(aFunction, aSequence)
list comprehension
lambda function
!A way to create small anonymous
functions, i.e. functions without a name.
! Mainly used in combination with the
functions filter(), map() and reduce().
! Syntax:
#Functional approach
add = lambda x, y : x + y
print(add(2,3))
Output:
5
! Ex:
f = lambda x: x<100
print(f(90))
Output:
True
! Ex:
f = lambda x: 'big' if x > 100 else 'small'
print(f(100))
Output:
small
Map() function
! Themap(aFunction, aSequence) function
applies a passed-in function to each item
in an iterable object and returns a list
containing all the function call results.
! Ex:
items = [1, 2, 3, 4, 5]
def sqr(x):
return x ** 2
print(list(map(sqr, items)))
Output:
[1, 4, 9, 16, 25]
! Ex:
#python 3
items = [1, 2, 3, 4, 5]
print(list(map((lambda x: x **2), items)))
#python 2
items = [1, 2, 3, 4, 5]
print(map((lambda x: x **2), items))
! While we still use lamda as a aFunction, we can
have a list of functions as aSequence.
! Ex:
def square(x):
return (x**2)
def cube(x):
return (x**3)
funcs = [square, cube]
for r in range(5):
value = list(map(lambda x: x(r), funcs))
print(value)
! Output:
[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]
! Multiple iterables to the map function
! Ex:
a = [1, 2, 3]
b = [10, 20, 30]
print(list(map(lambda x, y: x + y, a, b)))
Output:
[11,22,33]
filter() function
! Thefilter(aFunction, aSequence) function
applies a passed-in function to each item
in an iterable object and extracts each
element in the sequence for which the
function returns True.
! Ex:-
list(range(-5,5))
# [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
print(list(filter((lambda x: x < 0), range(-5,5))))
print(list(map((lambda x: x < 0), range(-5,5))))
Output:-
[-5, -4, -3, -2, -1]
[True, True, True, True, True, False, False, False,
False, False]
Finding intersections of two lists
! Ex:
a = [1,2,3,5,7,9]
b = [2,3,5,6,7,8]
Output:-
[2, 3, 5, 7]
! Ex:
fib = [0,1,1,2,3,5,8,13,21,34,55]
result = filter(lambda x: x % 2, fib)
print(result)
result = filter(lambda x: x % 2 == 0, fib)
print(result)
Output:
[1, 1, 3, 5, 13, 21, 55]
[0, 2, 8, 34]
How filter() method works
without the filter function?
! Ex:
# random list
randomList = [1, 'a', 0, False, True, '0']
filteredList = filter(None, randomList)
print('The filtered elements are:')
for element in filteredList:
print(element)
! Output:
Output:
24
! Ex:
Output:
0.041666666666666664
! Determining the maximum of a list of
numerical values by using reduce:
Output:
102
! Calculating the sum of the numbers from 1
to 100:
Output:
5050