unit1-part2
unit1-part2
Chapter 1- Functions
PYTHON FUNCTIONS
▪ A function is a block of code which only runs when it is called.
▪ You can pass data, known as parameters, into a function.
▪ A function can return data as a result.
▪ The objective is to define a function and group-specific frequently performed
actions. Instead of repeatedly creating the same code block for various input
variables, we can call the function and reuse the code it contains with different
variables.
▪ Creating a Function
▪ In Python a function is defined using the def keyword:
▪ def my_function():
print("Hello from a function")
▪ my_function()
FUNCTION ARGUEMENT
▪ Information can be passed into functions as arguments.
▪ Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
▪ def my_function(fname):
▪ print(fname + " Refsnes")
▪ my_function("Heena")
▪ my_function("Afreen")
▪ my_function("Asifa")
▪ Parameters or Arguments?
▪ The terms parameter and argument can be used for the same thing:
information that are passed into a function.
▪ A parameter is the variable listed inside the parentheses in the function
definition.
▪ An argument is the value that is sent to the function when it is called.
▪ Number of Arguments
▪ By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
▪ Example
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Heena", "Shaikh")
ARBITRARY ARGUMENTS, *ARGS
▪ If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition.
▪ This way the function will receive a tuple of arguments, and can access the items
accordingly:
▪ Example
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Heena", "Afreen", "Zam")
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
ANONYMOUS/LAMBDA FUNCTIONS
▪ Since we do not use the def keyword to declare these kinds of Python functions, they are
unknown. The lambda keyword can define anonymous, short, single-output functions.
▪ Arguments can be accepted in any number by lambda expressions; However, the function only
produces a single value from them. They cannot contain multiple instructions or expressions.
▪ Syntax
▪ Lambda functions have exactly one line in their syntax:
Example:
▪ x = lambda a : a + 10
print(x(5))
▪ o/p 15
▪ Example 2:
▪ x = lambda a, b : a * b
print(x(5, 6))
▪ Example 3:
▪ x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
OPTIONAL ARGUMENTS
▪ An argument is a value that is passed to the function when it is called. Sometimes, we
need to have optional arguments as well, which means even if we will not pass the
values, the program shouldn't return any error.
▪ We can specify a default value for an argument using the assignment operator.
▪ Example:
# python function
def main(num):
# return value of function
return num*num
# calling function without argument
print(main())
optional arguments with default arguments
▪ Python has a different way of representing syntax and default values for function arguments. Default values indicate that
the function argument will take that value if no argument value is passed during the function call. The default value is
assigned by using the assignment(=) operator of the form keywordname=value.
➢ Default argument
# Python optional arguments with default argument
def main(num1, num2, num3 = 0):
# return the sum of the arguments
return num1+num2 +num3
# calling the function with two arguments
print("the sum is: " ,main(10,5))
Notice that the default value of the argument was replaced by the new and updated value. 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 which means non-default arguments cannot follow default arguments.
For example, a non-default argument cannot be on the left side of the default one.
MUTABLE OPTIONAL PARAMETERS
▪ If the optional parameter is a mutable type, like a list or dictionary, and it’s changed in
the function, the change will propagate through all the following calls.
▪ Example:
def list_appender(item, items = []):
items.append(item)
return items
print(list_appender("hello"))
print(list_appender("salut"))
print(list_appender("hallo")) o/p→
print(list_appender("hola"))
▪ Here we have a function that has one optional parameter, an empty list. In the function the
object passed as the first parameter, which is mandatory, is appended to the list. When the
function is called for the first time, the optional parameter is evaluated. In the function the
element “hello” is appended to the list and the list with the “hello” string is returned. But when
the function is called for the second time, the optional parameter is not evaluated again, so the
function works on the list with the element appended before, not on an empty list like the first
time. In the following calls the new element is appended to the list which already contains all
the elements appended in the earlier function call.
PYTHON FUNCTION RECURSION
▪ 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.
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
o/p→
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
▪
UNPACKING ITERABLES
The unpacking operator in Python is used to unpack an iterable object into individual
elements. It is represented by an asterisk sign * and has the following syntax.
▪ Syntax
*iterable_object
•The iterable_object variable represents an iterable object such as a list, tuple, set, or a Python dictionary.
Example:
myList=[1,2,3,3,4,4,5,6]
mySet={*myList}
print("The list is:")
print(myList)
print("The set is:")
print(mySet)
▪ Inthe above example, the * operator unpacks myList. Then, we created a set from
the unpacked elements.
▪ Instead of using the * operator, you can unpack an iterable object into multiple variables
using parallel assignment. For this, you can use the following syntax.
▪ Syntax
▪ var1, var2, var3,var4..varN=iterable_object
myList=[1,2,3,4,5,6]
print("The list is:")
print(myList)
a,b,c,d,e,f=myList
print("The variables are:")
print(a,b,c,d,e,f)
In the above syntax, the number of variables must be equal to the number of elements in the iterable_object.
Otherwise, the program will run into error.
➢ Unpacking Using The * Operator in Python
▪ When we have less number of variables than the elements in the iterable object, we can use the * operator to
unpack the iterable object using the following syntax.
In the above syntax, If there are more than N elements in the iterable_object, first N objects are assigned to the
variables var1 to varN. The rest of the variables are packed in a list and assigned to the variable var. You can observe this in the
following example.
Example:
myList=[1,2,3,4,5,6]
print("The list is:")
print(myList)
a,b,c,*d=myList
print("The variables are:")
print(a,b,c,d)
UNPACK DICTIONARY IN PYTHON
▪ Unpacking a dictionary means unloading and printing the key-value pairs or
loading them in other objects like a tuple or a list. We also unpack a dictionary
while sending their values to a function or when we are merging two dictionaries.
Using the Unpack Operator (**)
Example:
d = {'k1':10, 'k2':20, 'k3':30}
def fun(k1,k2,k3):
print(k1,k2,k3)
fun(**d)
Example:1
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
def print_person(name, age, city):
print(f"{name} is {age} years old and lives in {city}")
print_person(**my_dict)
Example2:
numbers = {"one": 1, "two": 2, "three": 3}
letters = {"a": "A", "b": "B", "c": "C"}
combination = {**numbers, **letters}
print(combination)
➢ The map() function
▪ The map() function takes two arguments: a function and an iterable. The function contention is the
function that will be applied to every element of the iterable, and the iterable contention is the
iterable that the function will be applied to. Here is the syntax of the map() function:
syntax
map(function, iterables)
function - a function
iterable - an iterable like sets, lists, tuples, etc
Example:
numbers = [2, 4, 6, 8, 10]
# converting to list
squared_numbers = list(squared_numbers_iterator)
print(squared_numbers)
Python example program for map() function
▪ Utilizing map() to convert temperatures from Celsius to Fahrenheit
temperatures = [0, 10, 20, 30, 40]
# lambda function defines the conversion formula
fahrenheit_temperatures = list(map( lambda x : (9/5)*x + 32, temperatures ))
▪ The reduce() function in python is a part of the functools module and doesn't return multiple values; it just returns
a single value.
▪ The reduce() function in python is a part of the functools module and doesn't return multiple values; it just returns
a single value.
▪ Syntax:
functools.reduce(function, iterable)
Example:
from functools import reduce
nums = [1, 2, 3, 4]
ans = reduce(lambda x, y: x + y, nums)
print(ans)
o/p→ 10
The above python program returns the sum of the whole list as a single value result which is calculated by
applying the lambda function, which solves the equation (((1+2)+3)+4).
Example2:
from functools import reduce
# calculates the product of two elements
def product(x,y):
return x*y
ans = reduce(product, [2, 5, 3, 7])
print(ans)
CHAPTER 2
Array
ARRAY
• The Array is an idea of storing multiple items of the same type together, making it easier to calculate the
position of each element by simply adding an offset to the base value. A combination of the arrays could
save a lot of time by reducing the overall size of the code. It is used to store multiple values in a single
variable. If you have a list of items that are stored in their corresponding variables like this:
• car1 = "Lamborghini"
• car2 = "Bugatti"
• car3 = "Koenigsegg"
Array Representation:
An array can be declared in various ways and in different languages. The important points that should be
considered are as follows:
1.The index starts with 0.
2.We can easily find any elements within this Array using the Index value.
3.The length of the Array defines the capacity to store the elements. It is written like x[100], which means the
length of array x is specified by 100.
Example:
import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a)
• We can use the remove() method to remove the given item, and pop() method to remove an item at the
given index.
Example:
• import array as arr
numbers = arr.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers) # Output: array('i', [10, 11, 12, 13])
print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])
Output
• array('i', [10, 11, 12, 13])
12
array('i', [10, 11, 13])
Python Lists Vs Arrays
• In Python, we can treat lists as arrays. However, we cannot constrain the type of elements stored in a list. For
example:
• # elements of different types
a = [1, 3.5, "Hello"]
• If you create arrays using the array module, all elements of the array must be of the same numeric type.
Example:
import array
# Create an array of integers
my_array = array.array('i', [1, 2, 3, 4, 5]
# Print the original array
print("Original array:", *my_array)
# Reverse the array in place
my_array.reverse()
# Print the reversed array
print("Reversed array:", *my_array)
Output:
• Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
• The extend() function is simply used to attach an item from iterable to the end of the array. In
simpler terms, this method is used to add an array of values to the end of a given or existing array.
• Example
import array as arr
#creating an array with using extend method
# array with int type
a.extend([6,7,8,9,10])
a = arr.array('i', [1, 2, 3,4,5])
#printing original array #printing original array
print("\nThe array after extend :",end=" ")
print("The before array extend:", end =" ") for i in range(0,10):
for i in range (0, 5): print(a[i],end=" ")
print()
print (a[i], end =" ")
print()
Output:
▪ The before array extend : 1 2 3 4 5
Example:
import array
# Create an array of integers
my_array = array.array('i', [1, 2, 3, 4, 2, 5, 2])
# Count the number of occurrences of the element 2 in the array
count = my_array.count(2)
# Print the result
print("Number of occurrences of 2:", count)
Output
Number of occurrences of 2: 3
▪ Using fromlist() Method
▪ This method appends items from a list at the end of the array. It is equivalent to a.extend([x1,x2,..]) and
also for x in list: a.append(x).
▪ Note that for this to work, all the items in the list should be of the same type code as the array.
import array
a = array.array('i',[1,2,3,4])
print(a)
li = [10,9,8]
a.fromlist(li)
b=a.toString()
print("Array after appending the list is:",a)
MULTIDIMENSIONAL ARRAY IN PYTHON
▪ An array with multiple dimensions can represent relational tables and matrices and is
made up of many one-dimensional arrays, multi-dimensional arrays are frequently used
to store data for mathematical computations, image processing, and maintaining records.
▪ The following example will show the difference between the datatype of creating a 2D
array created by the standard way and by using the Numpy package.
▪ Example:
#creating 2D array without any package
arr1 = [[0]*3]*2
print(arr1)
print(type(arr1))
print("Output")
print(array_1)
▪ Three-dimensional (3D) array in Python
▪ Example:
import numpy as nmp
X = nmp.array( [ [ 1, 6, 7],
[ 5, 9, 2],
[ 3, 8, 4] ] )
print(X[1][2]) # element at the given index i.e. 2
print(X[0]) # first row
print(X[1]) # second row
print(X[-1]) # last row
print(X[:, 0]) # first column
print(X[:, 2]) # third column
print(X[:, -1]) # last column