11.3.1.1 write code in a programming language using functions Python. FunctionsA function in programming, or a subroutine, is a piece of program code that can be accessed from another place in the program. A function is a specially grouped set of commands that are executed sequentially but considered as a whole. In this case, the function may return (or not return) its result. Functions...
A function is declared before it is called. A function description begins with a command def, followed by the name of the function, and a list of arguments in parentheses. The arguments get their values from the main program. A colon is placed at the end of the function declaration line. Example,
. Example A function that prints the string "Hello!" and returns nothing
Passing Parameters to Function Arguments When we call a function we can pass actual values or variable values as parameters Example
We can send several parameters. The value of the first parameter goes to the first argument, the value of the second parameter goes to the second argument, etc. Example
Setting default values We can set default values for arguments. In this case, if we do not pass the parameter to the argument, then the default value of the argument is used, if we pass, then the value of the parameter is used. Example 1
Example 2
Example 3
If we pass parameters to default arguments, then the arguments get the value from the parameters. Example 4
Arbitrary Arguments (*args) If we do not know how many values will be passed to the arguments, then an arbitrary argument with an asterisk is used. Arbitrary argument packs values into a tuple. Example
Keyword arguments (**kwargs) A set of named arguments can be passed a keyword argument with two asterisks. Keyword argument packs values into a dictionary. Example
Example using *args and **kwargs
Questions:
Exercises: Ex. 1 Define parts of the function structure Tasks: Task 1. Write a Python function sum() that takes two numbers as input parameters and returns their sum. Task 2. Create a Python function length() that accepts a string as an argument and returns the length of the string. Task 3. Implement a Python function maximum() that takes an array of integers as input and returns the maximum value in the array. Task 4. Write a Python function sum() that takes several numbers as input parameters and returns their sum.
| |
| |
Просмотров: 4974 | | |
Всего комментариев: 0 | |