Module 4
Functions, Arrays and Fruitful Functions
4.1 return values
• A function takes arguments, performs some operations, and returns a
value.
• The value that a function returns to the caller is generally known as
the function's return value.
• Functions can return numeric values (int, float values), collections and
sequences of objects (list, tuple, dictionary, or set objects)
Example 1
def myfunc():
return 3+3
>>print(myfunc())
Output
6
Example 2
def division(a, b):
if b!=0:
return a/b
else:
return 0
print(division(4,2))
Output
2.0
print(division(2,0))
Output
0
Note: in else statement if return 1 is given then 1 will be the output
when print(division(2,0)) is given
4.2 Local and Global Scope
• Global variables can be accessed globally in the entire program,
whereas local variables can be accessed only within the function or
block in which they are defined.
• A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.
Example for local scope
• A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Output
300
print(x)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(x)
NameError: name 'x' is not defined
Global Scope
• A variable created in the main body of the Python code is a global variable
and belongs to the global scope.
• Global variables are available from within any scope, global and local.
Example
• A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
Output
300
print(x)
Output
300
4.3 Function Composition
Function composition is the way of combining two or more functions in
such a way that the output of one function becomes the input of the
second.
Example 1
>>>def add(x):
return x + 2
>>>def multiply(x):
return x * 2
#Adding 2 to 5 and multiplying the result with 2
>>>print(multiply(add(5)))
Output
14
Example 2
def sub(a):
return a-6
def divide(a):
return a/4
print(divide(sub(5)))
Output
-0.25
4.4 Recursion
In Python, it's also possible for a function to call itself! A function that calls
itself is said to be recursive, and the technique of employing a recursive
function is called recursion.
def greet():
print('Hello')
# recursive call
greet()
# normal function call
>>greet()
Output
Hello
Hello
Hello
.
.
.
The above program will call itself infinitely.
4.5 String Immutability
• In Python, strings have the property of immutability which means they
cannot be mutated or changed once it is created.
• You can assign strings to variables (program_name = „python‟) and reassign
new strings to the same variable (program_name = „java‟) but individual
characters within a string cannot be reassigned.
• Once an immutable object is created, its value remains permanent and
unchangeable.
• In Python, strings are made immutable so that programmers cannot alter the
contents of the object (even by mistake). This avoids unnecessary bugs.
Some other immutable objects are integer, float, tuple, and bool.
• Lists, dictionaries and sets are mutable.
Example
greet = "hi there!"
greet[0] = “w”
greet[0]=“w”
TypeError: 'str' object does not support item assignment
greet='123'
greet[0]=4
TypeError: 'str' object does not support item assignment
list is mutable
greet=[123]
greet[0]=4
print(greet)
Output
[4]
h=[123]
[Link](4)
print(h)
Output
[123, 4]
h=[„123‟]
[Link](4)
print(h)
Output
[„123‟, 4]
Dictionary mutable examples
grades={'arthur':90,'belle':60,'charles':80}
grades['charles']
Output
80
We can also add and change elements this way:
grades['charles']=45
grades['charles']
Output
45
We can add a new entry this way:
grades['das']=95
print(grades)
Output
{'arthur': 90, 'belle': 60, 'charles': 45, 'das': 95}
We can delete an item this way
del grades['belle']
print(grades)
Output
{'arthur': 90, 'charles': 45, 'das': 95}
4.6 string functions and methods
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title() and capitalize(): Convert string to title case i.e converts the first
character to upper case and rest to lower case.
swapcase(): Swap the cases of all characters in a string (upper case
character to lowercase and viceversa)
Example
1) text='PYTHON'
print([Link]())
Output
python
2) text='python'
print([Link]())
Output
PYTHON
3) print([Link]())
or
print([Link]())
Output
Python
4) text='vIDyaVIkas'
print([Link]())
Output
VidYAviKAS
5) Python String center() Method
Print the word “business", taking up the space of 20 characters, with
"business" in the middle:
txt="business"
print([Link](20))
Output
business
print([Link](90))
Output
business
4.7 String module
• It‟s a built-in module and we have to import it.
• ASCII (American Standard Code for Information Interchange)
import string
1) print(string.ascii_letters)
Output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
2) print(string.ascii_lowercase)
Output
abcdefghijklmnopqrstuvwxyz
3) print(string.ascii_uppercase)
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
4) print([Link])
Output
0123456789
5) print([Link])
• The hexadecimal number system is a type of number system, that has
a base value equal to 16.
• It is also pronounced sometimes as 'hex'.
• Hexadecimal numbers are represented by only 16 symbols.
• These symbols or values are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E
and F
Output
0123456789abcdefABCDEF
6) print([Link])
Output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
4.8 Python Arrays
• An array is a special variable, which can hold more than one value
at a time.
• An array is a collection of items stored at memory locations.
• The idea is to store multiple items of the same type together.
• If you have a list of items (a list of car names, for example), storing
the cars in single variable could look like this:
• car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
• If you want to loop through the cars and find a specific one, and if
you had not 3 cars, but 300, then the solution is an array!
• An array can hold many values under a single name, and you can
access the values by referring to an index number.
4.8.1 Access the Elements of an Array
Refer indexing in Module 1
4.8.2 Array Methods
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified
value
extend() Add the elements of a list (or any iterable), to the end
of the current list
index() Returns the index of the first element with the
specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
i) clear()
• Removes all elements from the fruits list
fruits = ['apple', 'banana', 'cherry', 'orange']
[Link]()
Output
Blank
or
fruits=['apple','banana','cherry','orange']
x=[Link]()
print(x)
Output
None
ii) copy()
• Returns a copy of the list
fruits = ["apple", "banana", "cherry"]
x = [Link]()
print(x)
Output
["apple", "banana", "cherry"]
iii) count()
• Returns the number of times the value "cherry" appears in
the fruits list
fruits = ['apple', 'banana', 'cherry' , 'cherry‟ ]
x = [Link](„cherry‟)
print(x)
Output
2
iv) extend()
Add the elements of cars to the fruits list
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
[Link](cars)
print(fruits)
Output
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
If 3rd list is added, then + operator is used to extend 3 lists
colours=[„red‟, „green‟]
[Link](cars+colours)
print(fruits)
Output
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo‟,„red‟,„green‟]
v) index()
What is the position of the value "cherry"
fruits = ['apple', 'banana', 'cherry']
x = [Link]("cherry")
print(x)
Output
2
vi) insert()
Adds an element at the specified position
fruits = ['apple', 'banana', 'cherry']
[Link](1, "orange")
print(fruits)
Output
['apple', 'orange', 'banana', 'cherry']
vii) pop()
Removes the element at the specified position
fruits = ['apple', 'banana', 'cherry']
[Link](1)
print(fruits)
Output
['apple', 'cherry']
viii) remove()
• Removes the first item with the specified value
fruits = ['apple', 'banana', 'cherry']
[Link]('banana')
print(fruits)
Output
['apple', 'cherry']
ix) reverse()
• Reverses the order of the list
fruits = ['apple', 'banana', 'cherry']
[Link]()
print(fruits)
Output
['cherry', 'banana', 'apple']
x) sort()
• Sorts the list ascending by default.
cars = ['Ford', 'BMW', 'Volvo']
[Link]()
print(cars)
Output
['BMW', 'Ford', 'Volvo']