5. Functions

¡Supera tus tareas y exámenes ahora con Quizwiz!

Lambda functions

- Anonymous functions in Python are called lambda functions. - Lambda functions offer a concise way to define functions without giving them a name. They are used to create and use functions on the fly. Lambda functions are usually passed as arguments to other functions. - syntax: lambda parameters: return_value - the above is a Python expression. It can appear in an assignment statement or as an argument to another function.

Summary of Arguments and Parameters

- The positional arguments always go first, followed by any keyword arguments. - The keywords must be chosen from the formal parameter names. - No arguments must receive a value more than once.

style guidelines for cs21a

- function names should be lower case, with words separated by underscore. Descriptive names are encouraged. - Function names typically describe operations applied to arguments by the interpreter or the name of the quantity that results. - Parameter names should be lowercase, with words separated by underscores, Single-word names are preferred. - Parameter names should describe the role of the parameter in the function, not just the type of value that is allowed. - Never use "I", "O" to avoid confusion with numerals.

What is a function

A function is a named sequence of statements. When we define a function, we specify its name and the sequence of statements. Later, we can call the function by name and the sequence of statements gets executed. In other words a function is a block of code that is defined once and is executed every time we call it. We say that a function takes an argument and returns a result. The result is called the return value.

Python module

A python module is basically a file that contains Python code. The module name is the file name without the extension. - python module starts with block comments that include information such as author and date. - the module itself has a docstring documenting its use. - given module may contain several function definitions.

DRY

Don't repeat yourself. The DRY principle is a central idea in software development. You should not have multiple fragments of code that performs the same thing - even if you can copy and paste the code into different locations. That results in code that is harder to test and harder to maintain. Instead, that logic should be implemented once given a name, and called multiple times.

Function composition

If we directly use the return value from one function as an input argument to another function.

Control flow

It is important to understand the control flow of the program to debug it and ensure its correctness in all corner cases. When Python interpreter encounters a module, it scans through the module. The comments and docstrings are ignored nu the interpreter. - The statements are executed from top to bottom, so the interpreter encounters the function definitions first. However the statements inside the function definition are NOT executed until the function is called. - So we get to the unindented statement: if__name__ == '__main__': - This is the only statement in the module that is not inside the function, and that is what is executed first. When we run the program from PyCharm or from the terminal, the value of the special variable __name__ is set to '__main__' so the condition for the if statement if True and the indented statement main() is executed. - so we go to the function main() and execute its statements one after another.

What's in a name

Naming rules in python: A identifier may be a variable name, a function name, a parameter name and so on. - identifier names are case sensitive. For ex: grade and Grade are not the same. - Identifiers must begin with a letter or an underscore - An identifier cannot be a reserved word. Reserved words are words that have a special meaning in Python such as True, False and else.

Function calls

Once we define our function, we can ask it a question by calling it. The function responds by returning a value. The initial values given to the parameters at the point of call are called the arguments. The return value of the function is accessed by writing function_name(arguments) Note that a return statement is not a print statement.

Arguments and parameters

Parameters are the variables in the function definition. Parameters appear in the function definition. Arguments are the values given to the variables at the point of call. Arguments appear in the function calls.

The main function

Place all our statements inside functions. function definitions don't execute any code without any function calls. This rule also applies to the main function. So we need to add a function call to main()

Pure functions and side effects

Pure functions are supposed to take an input and return a result with no side effects such as changing the mutable data items. Programmer should be careful about side effects because side effects are often the source of bugs in our programs. It is best to avoid then when possible.

Required positional arguments

Required positional arguments are the arguments passed to a function in correct positional order. the number of arguments in the function call must match the number of parameters in the function definition.

Print function arguments

The print function has optional parameters sep and end. We can use the keyword arguments to bypass the default. sep defaults to a space character ' '. end defaults to new line '\n'. If we want to specify a different separator, we specify it as follows. print ('Hello', 'World', sep='|') Hello|World If we don't want a new line between print functions calls, we use: print('Hello', end=' ') # use space character instead of a new line print('World') # when end is omitted, the default is used, Hello World

Functions and variable scope

The scope of an identifier refers to the part of the program where that identifier is visible, where it can be accessed. - Because variables are not declared ahead of time, Python uses the location of code in that function definiton. We cannot refer to these variables from outside the function. - Order does matter. We can only access a variable in our scope after it has been assigned value. The scope of a variable in a function extends from the assignment declaration until the end of a function. It does not include code that came before the assignment statement. - The parameters defined inside a function definition can be seen by the code in that function definition. The only other place that we can refer to them is in the function call. - Variables defined inside one function definition do not conflict with variables defined in other function definitions. The same name may be used in different functions. - we can use the keyword parameter number outside the function definition. However we cannot access the parameter number outside the function definition and outside the function call. Same variable name can be used in different functions.

Function Definition

To create our own function, we write a function definition. A function definition starts with the reserved word def followed by the function name. ex: def area(length, width): - Pythonic function names are lower case. - Note that the parameters do not have a type associated with them in the function definition. So it is a good practice to list the parameters in the function doc. - The function definition header ends with a colon. - Everything in a function definition is indented. The first line that is not indented is outside the function. There are no curly braces an no begins and ends to limit the function otherwise. - A function has its own docstring. It is the first thing within the function definition. It is also indented. Because the parameters and return value do not have a type associated with them in the function definition. It is a good practice to list them in the function docstring and list their expected type. It makes it easier to avoid errors when some other programmer is calling functions that we have defined. - A function may or may not have a return statement. The return statement causes the function to exit, and may or may not pass back in expression as in : return

Global variables?

Variables defined in the outer statements outside any function are called global variables. - we'll avoid using them in our programs because they result in code that is less readable, harder to debug and more difficult to maintain. Please note that it is NOT OK to use global variables in your programming assignments. - global constants are especially useful when the same constant is used in several functions. - use parameters and return values instead of global variables to communicate between functions.

Default Argument

When we define a function, we can provide default values for its arguments. When calling that function, arguments with default values are optional. If they are not provided, then the default value is used instead. Non-default parameters must appear before default parameters in the function definition. valid definition: def valid_diff(first, second = 0): invalid definition def invalid_diff(first = 0, second): Once we have specified the default parameters in the function definition, we can omit the corresponding arguments in the function call. Warning: Do NOT use a default value for a mutable object such as a list. This results in unexpected behavior.

Python module: if __name__ == '__main__':

if __name__ == '__main__': before the call to main, outside any function. - This is to allow the module to be imported and have its functions, classes or definitions used by some other module. - When a module is run directly, the special variable "__name__ == '__main__':. In this case, the main function will be executed. - However when the module is imported the function main will not be executed. We"ll see later how to import a module and use its function in another module. - From now on we will be adding if __name__=='__main__': as shown above to all our Python files to make them valid modules that can be either run directly or imported.

Lambda function examples

lambda function examples: example 1: square = lambda x: x ** 2 Now the variable square is a function. >>> square(5) 25 The above is equivalent to the following: def square(x): return x ** 2 Example 2: f = lambda word: word.lower() Now the variable f is a function. >>> f('HELLO') 'hello' The above is equivalent to the following function definition: define f(word): return word.lower() Example 3: add = lambda a, b: a + b The above is equivalent to the following function definition: def add(a, b): return a + b

Keyword Arguments

we can also call a function using keyword arguments of the word "keyword =value". We just have to identify the arguments by the parameter name. This allow us to list the arguments out of order because the interpreter is able to use the keywords provided to match the values with parameters. The order of the arguments does not matter because the arguments are matched with the parameter names. Note however that keyword arguments have to be specified AFTER non-keyword arguments. This will result into error print(area(length=5, 2)) No argument must receive a value more than once. print(area(2, length=5)) However, following is ok: print(area(2, width=5))


Conjuntos de estudio relacionados

Chapter 3 quiz: missed questions

View Set

AP 1 Ch 13 Spinal Cord/Spinal Pathways

View Set

Research Workshop: Writing and Presenting the Argumentative Essay, Part 2

View Set

Hero's Jounrey Review EXAMPLE - Moana

View Set

AP English Language Companion Journal Study Guide

View Set

Insurance Adjustor Exam Practice Questions

View Set

Sixth Extinction Crisis Plans and some animal phyla

View Set