Computer Science
Functions in Python
Functions in Python are reusable blocks of code that perform a specific task. They allow for better organization and reusability of code by breaking it into smaller, manageable pieces. Functions can take input parameters, perform operations, and return results. They are a fundamental concept in Python programming and are used extensively for modular and efficient code development.
Written by Perlego with AI-assistance
Related key terms
1 of 5
8 Key excerpts on "Functions in Python"
- eBook - ePub
Python Made Simple
Learn Python programming in easy steps with examples
- Rydhm Beri(Author)
- 2019(Publication Date)
- BPB Publications(Publisher)
HAPTER 5Functions
Introduction
A function is a self-contained block of statements that can repeatedly be executed whenever we need it in a program. The concept of a function is very useful and is used in every programming language like C, C++, Java, Python, and so on. Functions are used to provide the functional programming feature to the programming language. Some languages like C, C++, and Java do not allow you to write even a single program without using functions. But in Python, we can create our programs even without using functions. The advantage of functions while writing a Python program is that it allows the programmer to include extra features in the Python program. In this chapter, we will focus on Python functions. We will describe the different types of functions used in a Python program. We will also discuss the different methods used to pass arguments to the functions and other concepts related to the functions.Structure
- Introduction to functions
- Difference between functions and methods
- Advantages of using functions
- Classification of functions
- Components of user-defined functions
- Categories of functions
- Passing Argument to functions
- Scope of a variable
- Recursion
- Lambda functions
Objectives
- Understanding the concept of functions and their usage in programming
- Understanding the classification of functions
- Understanding the different components of functions
- Knowing the parameter passing techniques of a function
- Understanding the concept of recursion
- Knowing the role of lambda functions
Introduction to functions
Python programming is useful to solve large problems in an easy and efficient manner. Sometimes, it is difficult to solve the complex problems at large extent. In order to manage complex problems, they can be broken down into the smaller subproblems, then these subproblems can be solved separately; this reduces the complexity of the program. These subproblems are considered as program routines. - eBook - ePub
Programming in Python
Learn the Powerful Object-Oriented Programming
- Dr. Pooja Sharma(Author)
- 2018(Publication Date)
- BPB Publications(Publisher)
HAPTER 6Python Functions
Highlights
- Python functions
- Types of functions
- Advantages of functions
- Python user defined functions
- Python anonymous functions
- Pass by value vs. pass by reference
- Recursion
In programming, sometimes a similar code has to be repeated at many places in a program. For which, the programmer needs to write the same set of instructions several times. For example, while computing a binomial coefficient, the factorial needs to be computed several times. It would waste the programmer's time and effort to write the same code again and again. This activity not only increases the size of the program but also leads to typographical errors. To overcome this issue, the Python programming language is provided with the feature called subprograms or functions. A subprogram or function is a name given to a set of instructions that can be called by another program or a subprogram. This technique simplifies the programming process to a great extent because a single set of instructions in the form of a subprogram is being used for all instances of computational requirements with only change in the supplied data.6.1. Python Functions
In Python programming language, a function is a self-contained group of statements, which are intended to perform a specific task. Functions break the program into smaller modules, which perform a particular operation and are easy to understand. The large programs become more manageable and organized by using the concept of functions.6.2. Advantages of Functions
- Avoids Repetition: functions avoid repetition of the similar code again and again. The same code of a function can be used several times by different parts of the program or by different programs.
- Modularization:
- eBook - ePub
Python for Everyone
Learn and polish your coding skills in Python (English Edition)
- Saurabh Chandrakar, Dr. Nilesh Bhaskarrao Bahadure(Authors)
- 2023(Publication Date)
- BPB Publications(Publisher)
HAPTER 6Concept of Functions in Python
Introduction
Sometimes during programming a code, we are required to use the same code again and again. As per the Don’t Repeat Yourself (DRY ) concept, the same code should not be repeated multiple times during programming. Nonetheless, sometimes we need to use a block of code multiple times. In such cases, Functions in Python come handy.Functions play a huge role in our Python code. An important point to note is that functions must be defined initially before being later called in Python with proper indentation. Functions in Python are important as a coder, because DRY concept must be respected, while creating any big project makes that any 3rd party coder understand its importance.Structure
In this chapter, we will discuss the following topics:- Functions in Python
- Function types
- Function arguments
- Nested function
- Python closures
- Function passing as a parameter
- Local, global, and non-local variables
- Recursive function
- Python lambda functions
Objectives
By the end of this chapter, the reader will have an idea about what exactly function is in Python. They will have a taste of various arguments such as positional, keyword, default, *args and **kwargs. The concept of local, global, and non-local variables will be well explained. We shall see how to bind the data to a function without passing them as parameters called closures. One function will be defined inside another function using nested function concept. We shall see recursive function, that is, a function calling itself. Anonymous functions taking any number of arguments with one expression will be seen by exploring the concept of lambda functions.Functions in Python
It is not recommended to write group of statements repeatedly to execute the program. The group of statements will be defined as a single unit, thus breaking our program into smaller and modular chunks. We name this group of statements as functions, which performs a specific task. Code reusability is possible and repetition is avoided. We will be writing function only once, but the function will be called multiple times. The basic syntax of function is as follows: - Jose M. Garrido(Author)
- 2015(Publication Date)
- Chapman and Hall/CRC(Publisher)
In addition to calling programmer-defined functions, the instructions in the program can call built-in functions provided by standard Python inter-preter libraries or by other Python modules. A library is a collection of related function definitions and/or class definitions that may also include data. As mentioned in the previous chapter, a function starts executing when it 47 48 squaresolid Introduction to Computational Models with Python is called by an instruction in the program. Before a function can be called in a Python program, a function definition is required. Once a function is defined, it can be called or invoked one or more times. 3.3 FUNCTIONS A Python program is often decomposed into modules, and these are divided into classes and functions. A function carries out a specific task in a program. The data in a function is known only to that function—the scope of the data is local to the function. The local data in a function has a limited lifetime; it only exists during execution of the function. A Python program typically consists of functions and instructions that call or invoke the various functions. In the source code, the general syntactical form of a function definition in the Python programming language is written as follows: def function_name ( [parameters] ) : [ local declarations ] [ executable language statements ] The relevant internal documentation of the function definition is described in one or more lines of comments, which begin with the characters (”””) and ends with (”””). The local data definitions in the function are optional. The instructions implement the body of the function. 3.3.1 Function Calls After a function is defined, it can be called (invoked) and the name of the function is used by the instruction in the program that calls the function. When a function is called, the normal sequential flow of control is altered and the (called) function starts execution immediately. Figure 3.1 A function call.- No longer available |Learn more
- Oswald Campesato(Author)
- 2022(Publication Date)
- Mercury Learning and Information(Publisher)
FUNCTIONALLY ORIENTED PROGRAMMING IN PYTHONThe distinction between function and method is whether the function is defined in a class or not. Functions in a module are just functions, functions in class are methods of the class or methods of the resulting objects.In addition, function is a more general term (all methods are functions but not all functions are methods). Thus, the word function is used as a “generic term,” whereas the word method is used specifically with regard to classes or objects (the method of the list type, the methods of the str type, and so forth).Python supports methods (called iterators in Python 3), such as filter() , map() , and reduce() that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list. These iterators are discussed in the following subsections.The Python filter() FunctionThe filter function enables you to extract a subset of values based on conditional logic. The following example returns a list of odd numbers between 0 and 15 inclusive that are multiples of 3:>>> range(0,15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> def f(x): return x % 2 != 0 and x % 3 == 0 ... >>> filter(f, range(0, 15)) [3, 9] >>>The Python map() FunctionThe Python map() command is a built-in function that applies a function to each item in an iterable. The map(func, seq) calls func(item) , where item is an element in a sequence seq , and returns a list of the return values.Listing 5.1 displays the contents of Map1.py that illustrates how to use the map() function to compute the cube and fourth power of a set of numbers.Listing 5.1: Map1.py def cube(x): return x*x*x def fourth(x): return x*x*x*x x1 = map(cube, range(1, 5)) x2 = map(fourth, range(1, 5)) print (x1) print (x2)Listing 5.1 starts with the definition of two functions called cube() and fourth() , each of which takes a single numeric value. The cube() function returns the cube of its argument, and the fourth() - No longer available |Learn more
Python 3
Pocket Primer
- James R. Parker(Author)
- 2017(Publication Date)
- Mercury Learning and Information(Publisher)
And the ability to use a function as a variable value and a return result are a natural consequence of Python having no specific type connected with a variable at compilation time. There are many specific reasons to use functions in this way, on the other hand. Imagine a function that plots a graph. Being able to pass this function another function to be plotted is surely the most general way to accomplish its task. Recursion Python functions can be recursive. Recursion refers to a way of defin- ing things and a programming technique, not a general language feature. Something that is recursive is defined at least partly in terms of itself. When talking about functions, a function is recursive if it contains within it a call to itself. This is normally done only when the thing that it is attempting to accomplish has a definition that is recursive. Recursion as a programming technique is an attempt to make the solution simpler. If it does not, then it is inappropriate to use recursion. Each call to a function can be thought of as an instance of that function, and it will create all of the local variables that are declared within it. Each instance has its own copy of these, including its parameters, and each call returns to the caller as occurs with any other function call. 90 • PYTHON 3 POCKET PRIMER One important use of recursion is in reducing a problem into smaller parts, each of which has a simpler solution than does the whole problem. An example of this is searching a list for an item. If names = [Adams, Alira, Attenbourough, . . .] is a Python list of names in alphabetical order, answer the question: “Does the name Parker appear in this list?” Of course these is a built-in function that will do this, but this example is a pedagogical moment, and anyway perhaps the built-in function is slower than the solution that will be devised here. The function will return True or False when passed a list and a name. - No longer available |Learn more
Python 3
Pocket Primer
- James R. Parker(Author)
- 2017(Publication Date)
- Mercury Learning and Information(Publisher)
Why would any of these seemingly odd aspects of Python be useful? Allowing a general case, permitting the most liberal interpretation of the language, would permit unanticipated applications, of course. And the ability to use a function as a variable value and a return result are a natural consequence of Python having no specific type connected with a variable at compilation time. There are many specific reasons to use functions in this way, on the other hand. Imagine a function that plots a graph. Being able to pass this function another function to be plotted is surely the most general way to accomplish its task.RecursionPython functions can be recursive. Recursion refers to a way of defining things and a programming technique, not a general language feature. Something that is recursive is defined at least partly in terms of itself. When talking about functions, a function is recursive if it contains within it a call to itself. This is normally done only when the thing that it is attempting to accomplish has a definition that is recursive. Recursion as a programming technique is an attempt to make the solution simpler. If it does not, then it is inappropriate to use recursion.Each call to a function can be thought of as an instance of that function, and it will create all of the local variables that are declared within it. Each instance has its own copy of these, including its parameters, and each call returns to the caller as occurs with any other function call.One important use of recursion is in reducing a problem into smaller parts, each of which has a simpler solution than does the whole problem. An example of this is searching a list for an item. If names = [Adams, Alira, Attenbourough, . . .] is a Python list of names in alphabetical order, answer the question: “Does the name Parker appear in this list?” Of course these is a built-in function that will do this, but this example is a pedagogical moment, and anyway perhaps the built-in function is slower than the solution that will be devised here.The function will return True or False - eBook - PDF
Numerical Methods with Python
for the Sciences
- William Miles(Author)
- 2023(Publication Date)
- De Gruyter(Publisher)
3.3 Defining and using mathematical functions � 17 Examining the previous code, we see that the contents of coursename are converted to all uppercase letters in line 4. When the converted string, Ucourse, and the original name are printed in line 5, we see that the original variable contents are unchanged. In line 7, the uppercase string is searched for the uppercase substring. Thus, since all letters are uppercase, there is no case sensitivity. There are many other string methods available. Essentially, if you want to do some- thing with strings, your first step should be to Google what you want with ‘Python’ in- cluded in the search terms. It is likely that a method is already included among the re- turned content. See Exercises 2–4. 3.3 Defining and using mathematical functions We have seen that Python has many mathematical functions (including trigonometric, exponential, and logarithmic functions) available via the math and numpy libraries. However, it is often the case that we would like to define our own functions and be able to access them in a convenient fashion. We can do this in Python by using the def structure. Suppose we wish to define and use the function f (x) = 3x 2 − 2x + 1. We would begin by defining the function with the following. Code: 1 def f(x): 2 y = 3.0*x**2-2.0*x+1.0 3 return y The code starts with the def command followed by the name of the function. We can choose any name for the function. Generally, like variable names, function names tend to indicate the purpose of the function. In this case the function name is f. Following the function name is a list of inputs that the function will need in order to compute its value or perform its task. In this example, the function f requires a value for x in order to calculate the value of the function. In this example the value of the function is stored in the variable y. Finally, we must return the value of y. The indentation after the def declaration is important.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.







