unit1-part2.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
Unit 1-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 perfor...
Unit 1-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) my_function("Heena", "Afreen", "Zam") Arbitrary Arguments are often shortened to *args in Python documentations. KEYWORD ARGUMENTS ▪ You can also send arguments with the key = value syntax. ▪ This way the order of the arguments does not matter. ▪ Example: def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Raju", child2 = "Sonu", child3 = "Monu") Return Values To let a function return a value, use the return statement: 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. def main(keywordname = Value_assigned): # function's statements 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)) Example : the sum is: 15 # 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 print("the sum is: " ,main(10,5, 5)) o/p → the sum is: 20 ▪ Notice that the function was supposed to take three arguments but the third argument was optional because of its default value, we were able to get the returned value after passing two arguments. Example: # Python optional arguments with default argument def main(num1=0, num2, num3): # return the sum of the arguments return num1+num2 +num3 # calling the function with print("the sum is: " ,main(10,5, 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] # returns the square of a number def square(number): return number * number # apply square() to each item of the numbers list squared_numbers_iterator = map(square, numbers) # 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 )) # print the list of Fahrenheit temperatures print(fahrenheit_temperatures) FILTER() FUNCTION ▪ Python's built-in filter() function is a powerful too; for performing data filtering procedure on sequences like lists, tuples, and strings. The filter() function is utilized to apply a function to each element of an iterable (like a list or tuple) and return another iterable containing just the elements for which the function brings True back. Along these lines, filter() permits us to filter out elements from a grouping based on some condition. The first argument can be None if the function is not available and returns only elements that are True. ▪ Syntax filter (function, Iterable) ▪ Example: def filterdata(x): if x>5: return x # Calling function 0/p→ result = filter(filterdata,(1,2,6)) # Displaying result print(list(result)) Example: # Python filter() function example numbers = [ 1, -2, 3, -4, 5, -6 ] # Using filter() to remove negative numbers from the list result = list(filter(lambda x: x >= 0, numbers)) # Printing the result print(result) reduce() function ▪ 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, which means the length of array x is specified by 100. Creating Python Arrays To create an array of numeric values, we need to import the array module. For example: Example: import array as arr a = arr.array('d', [1.1, 3.5, 4.5]) print(a) o/p--> array('d', [1.1, 3.5, 4.5]) Accessing Python Array Elements import array as arr a = arr.array('i', [2, 4, 6, 8]) print("First element:", a) print("Second element:", a) print("Last element:", a[-1]) Output First element: 2 Second element: 4 Last element: 8 Changing and Adding Elements Example: import array as arr numbers = arr.array('i', [1, 2, 3, 5, 7, 10]) # changing first element numbers = 0 print(numbers) # changing 3rd to 5th element numbers[2:5] = arr.array('i', [4, 6, 8]) print(numbers) Output array('i', [0, 2, 3, 5, 7, 10]) array('i', [0, 2, 4, 6, 8, 10]) Removing Python Array Elements We can delete one or more items from an array using Python's del statement. import array as arr number = arr.array('i', [1, 2, 3, 3, 4]) del number # removing third element print(number) # Output: array('i', [1, 2, 3, 4]) del number # deleting entire array print(number) # Error: array is not defined 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. import array as arr # Error a = arr.array('d', [1, 3.5, "Hello"]) Reversing Elements in a Array In order to reverse elements of an array we need to simply use reverse method. 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 The array after extend : 1 2 3 4 5 6 7 8 9 10 Counting Elements in a Array In order to count elements in an array we need to use count method. 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 = [*3]*2 print(arr1) print(type(arr1)) #creating 2D array with numpy package print("\n") arr2 = np.array([[1,2,3,4], [5,6,7,8]]) print(arr2) print(type(arr2)) ▪ A 2D array in python is a two-dimensional data structure stored linearly in the memory. It means that it has two dimensions, the rows, and the columns, and thus it also represents a matrix. Implementing 2D array in Python Let’s start with implementing a 2 dimensional array using the numpy array method. arr = np.array([array1 values..][array2 values...]) Example: array_1 = np.array([[1,2,3,4], [5,6,7,8]]) 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) # element at the given index i.e. 2 print(X) # first row print(X) # second row print(X[-1]) # last row print(X[:, 0]) # first column print(X[:, 2]) # third column print(X[:, -1]) # last column