Python Unit 3 Notes
Python Unit 3 Notes
Unit-III
Function
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again. You can pass data, known as parameters, into a
function. A function can return data as a result.
Syntax:
Creating a Function
Example
def my_function():
print("welcome to python ")
Calling a Function
Example
def my_function():
print("welcome to python")
# call a function
my_function()
A parameter is the variable listed inside the parentheses in the function definition.
If you have experience in C/C++ or Java then you must be thinking about the return type of the
function and data type of arguments. That is possible in Python as well (specifically for Python 3.5
and above).
Syntax: Python Function with parameters
def function_name(parameter: data_type) -> return_type:
"""Doctring"""
# body of the function
return expression
The following example uses arguments that you will learn later in this article so you can come back
on it again if not understood. It is defined here for people with prior experience in languages like
C/C++ or Java.
return num3
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
Arguments of a Python Function
Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
In this example, we will create a simple function to check whether the number passed as an
argument to the function is even or odd.
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
Types of Arguments
Python supports various types of arguments that can be passed at the time of the function call. Let’s
discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments.
Output
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a default value. But
once we have a default argument, all the arguments to its right must also have default values.
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller does not need
to remember the order of parameters.
# Keyword arguments
student(firstname='Mukesh', lastname='Jha')
student(lastname='Jha', firstname='Mukesh')
Output
Mukesh Jha
Mukesh Jha
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
output:
apple
banana
cherry
Return statement in Python function
The Python return statement is used to return a value from a function. The user can only use the return
statement in a function. It cannot be used outside of the Python function. A return statement includes
the return keyword and the value that will be returned after that.
Syntax:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is returned to the
end of the function execution. If none of the above is present with the return statement a None
object is returned.
Example: Python Function Return Statement
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Output
4
16
output:
Enter a number: 10
The factorial of 10 is 3628800
Recursion
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called a recursive function. Recursion is an amazing technique with the
help of which we can reduce the length of our code and make it easier to read and write.
Properties of Recursion
• Performing the same operations multiple times with different inputs.
• In every step, we try smaller inputs to make the problem smaller.
• Base condition is needed to stop the recursion otherwise infinite loop will occur.
What is the base condition in recursion?
In the recursive program, the solution to the base case is provided and the solution to the bigger
problem is expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, the base case for n < = 1 is defined and the larger value of a number can be
solved by converting to a smaller one till the base case is reached.
Program to find factorial of a number using recursion
def factorial(x):
if x == 1:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))
Output:
Enter a number: 5
The factorial of 5 is 120
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
Output
enter the number of terms8
Fibonacci sequence:
0
1
1
2
3
5
8
13
• This Python scope contains the names that you define inside the function.
• These names will only be visible from the code of the function.
• It’s created at function call, not at function definition, so we have as many different local scopes as
function calls.
• This scope contains all of the names that are defined at the top level of a program or a module.
• Names in this Python scope are visible from everywhere in your code.
Let’s look at an example that demonstrates scope ideas. Suppose we write the following code in a
module file:
# global scope
X = 99 # X and func assigned in module: global
This module, and the function it contains, use a number of names to do their business. Using Python’s
scope rules, we can classify the names as follows:
Python Lambda
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
Example
x = lambda a : a + 10
print(x(5))
Example
x = lambda a, b : a * b
print(x(5, 6))
Example
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another
function.
Say you have a function definition that takes one argument, and that argument will be multiplied with
an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
print(cube(7))
print(cube_v2(7))
Output
343
343
Python Function within Functions
A function that is defined inside another function is known as the inner function or nested function.
Nested functions are able to access variables of the enclosing scope. Inner functions are used so that
they can be protected from everything happening outside the function.
def f1():
s = 'My name is bandana'
def f2():
print(s)
f2()
f1()
Output
My name is bandana
Strings : Length of the string and perform Concatenation and Repeat operations in it. Indexing
and Slicing of Strings.
We use single quotes or double quotes to represent a string in Python. For example,
Here, we have created a string variable named string1. The variable is initialized with the
Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given in the below figure.
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from the given string.
Consider the following example.
H E L L O
-5 -4 -3 -2 -1
Slicing
Specify the start index and the end index, separated by a colon, to return a part of the string.
b = "Hello, World!"
print(b[2:5])
output:
llo
By leaving out the start index, the range will start at the first character:
Example
b = "Hello, World!"
print(b[:5])
output
Hello
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Output
llo, World!
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
b = "Hello, World!"
print(b[-5:-2])
output
orl
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
a = "Hello, World!"
print(a.upper())
Lower Case
Example
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to remove this
space.
Example
The strip() method removes any whitespace from the beginning or the end:
Example
a = "Hello, World!"
print(a.replace("H", "J"))
output
Jello, World!
Split String
The split() method returns a list where the text between the specified separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(","))
output
'Hello', ' World!'
String Concatenation
Example
a = "Hello"
b = "World"
c=a+b
print(c)
Example
a = "Hello"
b = "World"
c=a+""+b
print(c)
String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the string where
the placeholders {} are:
Example
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Character
An example of an illegal character is a double quote inside a string that is surrounded by double
quotes:
Example
You will get an error if you use double quotes inside a string that is surrounded by double quotes:
Example
The escape character allows you to use double quotes when you normally would not be allowed:
There are many operations that can be performed with strings which makes it one of the most
We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Output
False
True
• str1 and str2 are not equal. Hence, the result is False.
In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)
Output
H
e
l
l
o
In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'
# Output: 5
We can test if a substring exists within a string or not, using the keyword in.
print('a' in 'program') # True
print('at' not in 'battle') False
Besides those mentioned above, there are various string methods present in Python. Here are some of
those methods:
Methods Description
The escape sequence is used to escape some of the characters present inside a string.
Suppose we need to include both double quote and single quote inside a string,
Since strings are represented by single or double quotes, the compiler will treat "He said, " as the
print(example)
String Length
a = "Hello, World!"
print(len(a))
output
13
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = "Hello"
print(findLen(str))
output
13
String Concatenation
Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
Example
a = "Hello"
b = "World"
c=a+b
print(c)
Example
a = "Hello"
b = "World"
c=a+""+b
print(c)
str.format() is one of the string formatting methods in Python, which allows multiple substitutions
and value formatting. It concatenate elements within a string through positional formatting. The
curly braces {} are used to set the position of strings. The first variable stores in the first curly
braces and the second variable stores in the second curly braces. Finally, it prints the value “Hello
World”.
• Python3
var1 = "Hello"
var2 = "World"
print(var3)
Output
Hello World
Hello World
“,” is a great alternative to string concatenation using “+”. when you want to include single
whitespace. Use a comma when you want to combine data types with single whitespace in between.
var1 = "Hello"
var2 = "World"
Output
Hello World
The repetition operator is denoted by a '*' symbol and is useful for repeating strings to a certain
length.
Example:
Example:
As the name suggests, these Data Structures are built-in with Python which makes programming
easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in detail.
Lists
Lists are used to store data of different data types in a sequential manner. There are addresses
assigned to every element of the list, which is called as Index. The index value starts from 0 and goes
on until the last element called the positive index. There is also negative indexing which starts from -
1 enabling you to access elements from the last to first. Let us now understand lists better with the
help of an example program.
Creating a list
To create a list, you use the square brackets and add elements into it accordingly. If you do not pass
any elements inside the square brackets, you get an empty list as the output.
Output:
[]
[1, 2, 3, ‘example’, 3.132]
Adding Elements
Adding the elements in the list can be achieved using the append(), extend() and insert() functions.
• The append() function adds all the elements passed to it as a single element.
• The extend() function adds the elements one-by-one into the list.
• The insert() function adds the element passed to the index value and increase the size of the
list too.
my_list = [1, 2, 3]
1
2print(my_list)
3my_list.append([555, 12]) #add as a single element
4print(my_list)
5my_list.extend([234, 'more_example']) #add as different elements
6print(my_list)
7my_list.insert(1, 'insert_example') #add element i
8print(my_list)
Output:
[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]
Deleting Elements
• To delete elements, use the del keyword which is built-in into Python but this does not return
anything back to us.
• If you want the element back, you use the pop() function which takes the index value.
• To remove an element by its value, you use the remove() function.
Example:
Output:
[1, 2, 3, ‘example’, 3.132, 30]
[1, 2, 3, 3.132, 30]
Popped Element: 2 List remaining: [1, 3, 3.132, 30]
[]
Accessing Elements
Accessing elements is the same as accessing Strings in Python. You pass the index values and hence
can obtain the values as needed.
Output:
1
2
3
example
3.132
10
30
[1, 2, 3, ‘example’, 3.132, 10, 30]
example
[1, 2]
[30, 10, 3.132, ‘example’, 3, 2, 1]
Other Functions
You have several other functions that can be used when working with lists.
Output:
6
3
2
[1, 2, 3, 10, 10, 30]
[30, 10, 10, 3, 2, 1]
Mutable Sequence
If the value can change, the object is called mutable, while if the value cannot change, the object is
called immutable. Mutable sequences can be changed after creation. Some of Python’s mutable data
List comprehension offers a shorter syntax when you want to create a new list based on the values of
an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
Example
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
output
With list comprehension you can do all that with only one line of code:
example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
output
['apple', 'banana', 'mango']
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
The condition if x != "apple" will return True for all elements other than "apple", making the new list
contain all fruits except "apple".
print(list)
Output:
[0, 2, 4, 6, 8, 10]
print(matrix)
Output:
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
List Comprehensions vs For Loop
There are various ways to iterate through a list. However, the most common approach is to use
the for loop. Let us look at the below example:
# Empty list
List = []
List.append(character)
# Display list
print(List)
Output:
['p’,’y’,’t’,’h’,’o’,’n’,’p’,’r’,’o’,’g’,’r’,’a’,’m’]
Above is the implementation of the traditional approach to iterate through a list, string, tuple, etc.
Now list comprehension does the same task and also makes the program more simple.
List Comprehensions translate the traditional iteration approach using for loop into a simple
formula hence making them easy to use. Below is the approach to iterate through a list, string,
tuple, etc. using list comprehension.
# Displaying list
print(List)
Output:
['p’,’y’,’t’,’h’,’o’,’n’,’p’,’r’,’o’,’g’,’r’,’a’,’m’]
Dictionary
Dictionaries are used to store key-value pairs. To understand better, think of a phone directory where
hundreds and thousands of names and their corresponding numbers have been added. Now the
constant values here are Name and the Phone Numbers which are called as the keys. And the various
names and phone numbers are the values that have been fed to the keys. If you access the values of
the keys, you will obtain all the names and phone numbers. So that is what a key-value pair is. And in
Python, this structure is stored using Dictionaries. Let us understand this better with an example
program.
Creating a Dictionary
Dictionaries can be created using the flower braces or using the dict() function. You need to add the
key-value pairs whenever you work with dictionaries.
Output:
{}
{1: ‘Python’, 2: ‘Java’}
To change the values of the dictionary, you need to do that using the keys. So, you firstly access the
key and then change the value accordingly. To add values, you simply just add another key-value pair
as shown below.
Output:
{‘First’: ‘Python’, ‘Second’: ‘Java’}
{‘First’: ‘Python’, ‘Second’: ‘C++’}
{‘First’: ‘Python’, ‘Second’: ‘C++’, ‘Third’: ‘Ruby’}
• To delete the values, you use the pop() function which returns the value that has been deleted.
• To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key
and value.
• To clear the entire dictionary, you use the clear() function.
Output:
Value: Ruby
Dictionary: {‘First’: ‘Python’, ‘Second’: ‘Java’}
{}
Accessing Elements
You can access elements using the keys only. You can use either the get() function or just pass the
key values and you will be retrieving the values.
Output:
Python
Java
Other Functions
You have different functions which return to us the keys or the values of the key-value pair
accordingly to the keys(), values(), items() functions accordingly.
Output:
dict_keys([‘First’, ‘Second’, ‘Third’])
dict_values([‘Python’, ‘Java’, ‘Ruby’])
dict_items([(‘First’, ‘Python’), (‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])
Python
Tuple
Tuples are the same as lists are with the exception that the data once entered into the tuple cannot be
changed no matter what. The only exception is when the data inside the tuple is mutable, only then the
tuple data can be changed. The example program will help you understand better.
Creating a Tuple
Output:
(1, 2, 3)
Accessing Elements
print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])
Output:
1
2
3
edureka
(1, 2, 3, ‘edureka’)
1
(1, 2, 3, ‘edureka’)
e
Appending Elements
To append the values, you use the ‘+’ operator which will take another tuple to be appended to it.
my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)
Output:
(1, 2, 3, 4, 5, 6)
Other Functions
Output:
(1, 2, 3, [‘english’, ‘python’])
1
3
Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
* Note: Set items are unchangeable, but you can remove items and add new items.
Example
Create a Set:
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index
or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.
Example
print(thisset)
output
To determine how many items a set has, use the len() function.
Example
print(len(thisset))
output
3
Set Items - Data Types
Example
Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
type(set1)
output
set
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
output
<class 'set'>