Course On Python Basics UNIT – 6: FUNCTIONS IN PYTHON Structure 6.0 Learning Objectives 6.1 Introduction to Functions 6.2 Arguments of a Function in Python 6.3 Generators in Python 6.4 Recursive Functions in Python 6.5 Nested functions in Python (Python Closure) 6.6 Lambda Function in Python 6.7 First Class Functions in Python 6.8 Summary 6.9 Glossary 6.10 References Page 1 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 6.0 Learning Objectives After studying this unit, you will be able to: • Understand Functions in python programming • Define arguments of a Function in Python • Explain Generators in Python • Use Recursive Functions • Explain Lambda Function in Python • Understand First Class Functions in Python 6.1 Introduction to Functions A function is a piece of code that does a certain goal. It can be called numerous times and reused. You can provide data to a function, and it will return data to you. Many programming languages come with built-in functions that you may use from their libraries, but you can also write your own. The software will halt the current program and perform the function when you call a function. From top to bottom, the function will be read. The program resumes where it had halted after the function is completed. If a value was returned by the function, it will be utilized at the place where it was called. Functions can be written in a variety of ways. The syntax you choose will be determined by the programming language you use. In this course, the python programming language is used to demonstrate the use of functions. Page 2 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Python Functions are a group of connected statements that are used to accomplish a computational, logical, or evaluative activity in Python. The goal is to group together certain often performed actions and create a function, so that rather than writing the same code over and over for various inputs, we may call the function and reuse the code contained within it. Built-in and user-defined functions are both possible. It aids in keeping the program succinct, non-repetitive, and well-organized. Various types of functions available are as follows: • Void Functions: A void function is the first type of function we'll look at. Simply put, this indicates that the function doesn't return a value. To finish a series of instructions, void functions are employed. ‘HelloFunction’ is the name of the function we created in these examples. The function's aim is to print \"Hello World.\" • Functions with input values: If you find yourself writing the same code over and again, void functions come in handy. They can, however, be restrictive. They aren't moving and aren't changing. They follow the same guidelines every time. Passing various values to the function is one method to make them more helpful. We can state that data is required to run our function in brackets. The data given to our function may then be used in the function. Let's go Page 3 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics over the previous examples once more, but this time pass the sentence we wish to produce. • Functions with return values: Returning data is the last function ability we'll look at. This is very useful when you wish to change data before using it. Although you could do it inline, if you'll be doing the same computations often, such as changing imperial to metric, it's probably better to define it as a function. Our example will be straightforward. Our function will take two numbers and return the total of them. The procedure to create and call a function in python is as follows: • Creating a Function: Using the def keyword, we can create a Python function. Example: • Calling a Function: After constructing a function, we may call it by using the function's name followed by parentheses holding the function's parameters. Page 4 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 5 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 6.2 Arguments of a Function in Python The values given inside the function's parentheses are referred to as arguments. A comma separates any number of parameters in a function. Python accepts a variety of parameters that can be supplied to a function when it is called. Let's take a closer look at each type. • Default arguments: A default argument is a parameter that takes on a default value if no value is specified for it in the function call. Default parameters are demonstrated in the following example. Page 6 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Page 7 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Keyword arguments: We may use special symbols in Python to send a variable number of parameters to a function. There are two other symbols to be aware of: Special Symbols Used for passing arguments: - 1) *args (Non-Keyword Arguments) In Python function definitions, the special syntax *args is used to send a configurable number of arguments to a function. It's being used to pass a variable-length, non-keyworded argument list. ➢ To take in a variable number of arguments, use the symbol *; by convention, it is commonly combined with the term args. Page 8 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics ➢ You can use *args to take in more arguments than the number of formal arguments you defined earlier. Any number of additional arguments can be added to your current formal parameters with *args (including zero extra arguments). ➢ For instance, we'd want to create a multiply function that can accept any number of parameters and multiply them all together. *args can be used to accomplish this. ➢ When we use the *, the variable we link with the * becomes an iterable, which means we can iterate over it, perform higher-order functions like map and filter, and so on. Example: Page 9 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 2) **kwargs (Keyword Arguments) **kwargs is a special syntax used in Python function definitions to pass a keyworded, variable-length argument list. We call ourselves kwargs because of the double star. The reason for this is that the double star allows us to send keyword arguments through (and any number of them). ➢ When you provide a variable into a function as a keyword argument, you give it a name. ➢ The kwargs may be thought of as a dictionary that matches each term to the value we provide along with it. That's why there doesn't appear to be any sequence in which the kwargs were printed out when we iterate through them. Example: Page 10 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Page 11 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 6.3 Generators in Python A generator, in simple terms, is a function that returns an object (iterator) that we may iterate through (one value at a time). In Python, creating a generator is quite straightforward. It's the same as defining a regular function, but instead of a return statement, you'll use a yield statement. A function becomes a generator function if it includes one yield statement (it may also have other yield or return statements). From a function, both yield and return will return a value. Page 12 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics The distinction is that a return statement closes a function completely, but a yield statement pauses it and saves all of its states before continuing on subsequent calls. A generator function varies from a regular function in the following ways: • One or more yield statements can be found in the generator function. • It returns an object (iterator) when called, but does not start execution right away. • Methods like __iter__() and __next__() are automatically implemented. As a result, we can use next to iterate through the objects (). • The function is halted and control is passed to the caller once the function yields. • Between calls, local variables and their states are remembered. • Finally, after the function finishes, StopIteration is automatically raised on further calls. When we talk about generators, we have two types: 1) Generator-Function: A generator function is defined similarly to a regular function, except that when it needs to create a value, it uses the yield keyword instead of the return keyword. If yield appears in the body of a def, the function is converted to a generator function. Page 13 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 14 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 2) Generator-Object: A generator object is returned by generator functions. Calling the very next method on the generator object or utilising the generator object in a \"for in\" loop are two ways to use generator objects (as shown in the above program). Page 15 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 16 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Applications of Generator: If we want to construct a stream of Fibonacci numbers, we can use the generator technique; all we have to do is use next(x) to receive the next Fibonacci number, and we don't have to worry about where or when the stream of numbers stops. Handling big data files, such as log files, is a more realistic use of stream processing. Generators are a space-saving solution for such data processing since only bits of the file are processed at a time. We could also use Iterators for this, but Generator is more convenient (we don't have to write the __next__ and __iter__ functions). Page 17 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 6.4 Recursive Functions in Python The practice of defining something in terms of itself is known as recursion. Place two parallel mirrors facing each other in the physical world as an illustration. Any item between them would be recursively mirrored. We know that a function in Python may call other functions. It's possible that the function will call itself. Recursive functions are the name for these sorts of constructs. The advantages of recursion are as follows: • Recursion can be used to break down a complex function into smaller sub-problems. • Recursion is more efficient than nested iteration for creating sequences. • The use of recursive functions makes the code appear simple and efficient. The disadvantages of recursion are as follows: • Recursive calls use a lot of memory and time, making it inefficient to utilize. • Debugging recursive routines is difficult. • The logic of recursion might be difficult to comprehend at times. Page 18 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 19 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 6.5 Nested Functions in Python (Python Closure) A nested function is a function that is defined inside another function. The variables of the enclosing scope can be accessed by nested functions. These non-local variables can only be accessed inside their scope in Python, not outside of it. Page 20 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 21 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Python Closures: Closures are function objects that remember values in enclosing scopes even if they aren't in memory. • It's a record that records a function and its environment: a mapping that links each of the function's free variables (variables that are used locally but declared in an enclosing scope) to the value or reference to which the name was bound when the closure was formed. • Unlike a regular function, a closure allows the function to access the captured variables via the closure's copies of their values or references, even if the function is called outside of their scope. Page 22 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 23 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Closures, as shown in the code above, allow you to call functions that aren't in your scope. The innerFunction function's scope is limited to the outerFunction. However, we can simply increase its scope by using closures to call a function that isn't in its scope. • When and why to use Closures: ➢ Closures provide some data concealing since they are utilised as callback functions. This allows us to use fewer global variables. ➢ Closures are an effective approach to write code when we just have a few functions. If we require a lot of functions, though, we should use a class. Page 24 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 6.6 Lambda Function in Python The term \"anonymous function\" in Python refers to a function that has no name. The def keyword is used to construct conventional functions, whereas the lambda keyword is used to create anonymous functions, as we already know. When we need a nameless function for a brief period of time, we employ lambda functions. We usually utilize it as an argument to a higher-order function in Python (a function that takes in other functions as arguments). Built-in functions such as filter(), map(), and others are combined with lambda functions. This function accepts any number of inputs but only evaluates and returns one expression. Lambda functions can be used whenever function objects are necessary. It's important to remember that lambda functions are syntactically limited to a single expression. Apart from other forms of expressions in functions, it has a variety of applications in certain domains of programming. Page 25 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 26 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: The print function does not invoke the lambda in this example; instead, it merely returns the function object and the memory address where it is stored. So, in order for the print to print the string, we must first run the lambda function in order for the string to pass the print. 6.7 First class Functions in Python In a programming language, first-class objects are treated consistently throughout. They can be utilized in control structures, supplied as arguments, and saved in data structures. If a programming language handles functions as first-class objects, it is said to support first-class functions. The idea of First Class functions is supported by Python. Page 27 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Functions of the first class have the following properties: • A function is an instance of the Object type. • The function can be saved in a variable. • The function can be sent as a parameter to another function. • From a function, you may return the function. • You may put them in data structures like hash tables, lists, and so on. Example: Page 28 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Functions in Python are first-class objects. We are assigning function to a variable in the example below. The function isn't called in this assignment. It generates a second name, yell, that points to the function object specified by shout. Output: 6.8 Summary In this module we have learned: • A function is a set of actions that are executed when the function is invoked. • The function may accept input parameters and do computations with them. • When a function is performed, it can also return values. Page 29 of 30 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics • We understood that generator functions can be used to declare a function that acts as an iterator and closures can access variables present in the outer function scope. • We also learned that when we need a nameless function for a brief period of time, we employ lambda functions and when we need a function to call itself we use recursive functions 6.9 Glossary • Inline Function: An inline function is one for which the compiler instead of constructing a distinct set of instructions in memory, transfers the code from the function specification straight into the code of the calling function. • Bits: In a computer, a bit (short for binary digit) is the smallest unit of data. A bit has only one binary value: 0 or 1. • Iterator: An iterator is a programming object that allows you to traverse a container, such as a list. • Fibonacci series: The Fibonacci number sequence Fn is described mathematically by the recurrence relation. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. 6.10 References • https://docs.python.org/3/ • https://docs.python.org/3/library/functions.html • https://docs.python.org/3/c-api/function.html • https://realpython.com/defining-your-own-python-function/ • https://www.learnpython.org/en/Functions Page 30 of 30 All Rights Reserved. Vol. TLE001/03-2022
Search
Read the Text Version
- 1 - 30
Pages: