Skip to content

Commit cddb2a4

Browse files
Dusch4593SSwiniarskiKTom101
authored
Moved bulk of Python: Functions info into separate entries (Codecademy#701)
* build/refactor: moved bulk of function info into separate entries * refactor/style: removed output comments from Codebytes * Update content/python/concepts/functions/functions.md Co-authored-by: SSwiniarski <[email protected]> * Update content/python/concepts/functions/terms/anonymous-functions/anonymous-functions.md Co-authored-by: SSwiniarski <[email protected]> * Update content/python/concepts/functions/terms/arguments/arguments.md Co-authored-by: SSwiniarski <[email protected]> * build/refactor: implemeneted remaining suggestions for review 1 * Update content/python/concepts/keywords/keywords.md Co-authored-by: KTom101 <[email protected]> * Update content/python/concepts/recursion/recursion.md Co-authored-by: KTom101 <[email protected]> * refactor: implemented more feedback from review 2 Co-authored-by: SSwiniarski <[email protected]> Co-authored-by: KTom101 <[email protected]>
1 parent 0f96a1e commit cddb2a4

File tree

6 files changed

+372
-214
lines changed

6 files changed

+372
-214
lines changed
Lines changed: 18 additions & 214 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
Title: 'Functions'
3-
Description: 'Defined using the def keyword, functions allow tasks to be performed multiple times within a program without having to rewrite the same code in multiple places.'
3+
Description: 'Functions are defined with the def keyword and allow tasks to be performed multiple times within a program without having to be rewritten'
44
Subjects:
55
- 'Computer Science'
66
- 'Data Science'
@@ -15,62 +15,32 @@ CatalogContent:
1515

1616
Some tasks need to be performed multiple times within a program. Rather than rewrite the same code in multiple places, a function may be defined using the `def` keyword. Function definitions may include parameters, providing data input to the function.
1717

18-
Functions may return a value using the `return` keyword followed by the value to return.
18+
## Syntax
1919

20-
```py
21-
# Define a function named my_function with parameter x
22-
23-
def my_function(x):
24-
return x + 1
25-
26-
# Invoke the function and print the result
20+
```pseudo
21+
def my_function(value):
22+
return value + 1
2723
28-
print(my_function(2)) # Output: 3
29-
print(my_function(3 + 5)) # Output: 9
24+
print(my_function(2))
25+
print(my_function(3 + 5))
3026
```
3127

32-
## Calling Functions
28+
Functions may return a value using the `return` keyword followed by a `value`. They can then be called, or invoked, elsewhere in the program. The output from the snippet above would look similar to this:
3329

34-
In Python, a preexisting function can be invoked, or called, by writing the name of the function followed by parentheses.
35-
36-
For example, the code provided would call the `do_homework()` function.
37-
38-
```py
39-
do_homework()
30+
```shell
31+
3
32+
9
4033
```
4134

4235
**Note:** Function names in Python are written in snake_case.
4336

44-
## Function Parameters
45-
46-
Functions often need outside data to achieve their intended task. This is where parameters can be used as placeholders for that data.
47-
48-
Parameters are variables that are declared in the function definition. They are usually processed in the function body to produce the desired result. When the function is called, each parameter is assigned the value which was passed as a corresponding argument.
49-
50-
For example, the function below contains parameters for a `character`, a `setting`, and a `skill`, which are used as inputs to write the first sentence of a book.
51-
52-
```py
53-
def write_a_book(character, setting, skill):
54-
print(character + " is in " +
55-
setting + " practicing " +
56-
skill + ".")
57-
58-
write_a_book("Naomi", "engineering school", "welding")
59-
```
60-
61-
The output will be:
62-
63-
```shell
64-
Naomi is in engineering school practicing welding.
65-
```
66-
67-
## Returning Values from Functions
37+
## Return Values
6838

6939
The `return` keyword is used to return a value from a Python function. The value returned from a function can be assigned to a variable which can then be used in the program.
7040

7141
In the example below, the `check_leap_year()` function returns a string that indicates if the passed parameter is a leap year or not.
7242

73-
```codebyte/py
43+
```py
7444
def check_leap_year(year):
7545
if year % 4 == 0:
7646
return str(year) + " is a leap year."
@@ -84,142 +54,20 @@ returned_value = check_leap_year(year_to_check)
8454
print(returned_value)
8555
```
8656

87-
## Default Values for Function Parameters
88-
89-
Function parameters can also be initialized to a default value. In the `calc_total()` function, there are `amount` and `discount` parameters.
90-
91-
- When the `discount` value is explicitly specified in the function call, that value is used.
92-
- Otherwise, the default value of 10 is used.
93-
94-
```py
95-
def calc_total(amount, discount=10):
96-
total = amount * (1 - 0.01 * discount)
97-
return total
98-
99-
calc_total(100) # Output: 90.0
100-
calc_total(250, 5) # Output: 237.5
101-
```
102-
103-
## Keyword Arguments
104-
105-
Unless specified otherwise, the arguments passed into a function are assigned to each parameter in the order in which they appear in the function signature. Thus, they are also known as "positional arguments".
106-
107-
Python also supports keyword arguments — prefixing arguments with the names of parameters to assign them directly, regardless of the order.
108-
109-
```py
110-
def write_a_book(name, color, clothing_item):
111-
print(name + " was wearing a " + color +
112-
" " + clothing_item + ".")
113-
114-
write_a_book(color="yellow", clothing_item="raincoat", name="Jonas")
115-
```
116-
117-
The output will be:
118-
119-
```shell
120-
Jonas was wearing a yellow raincoat.
121-
```
122-
123-
Keyword arguments must be passed after positional arguments.
124-
125-
```py
126-
write_a_book(name="Jonas", "yellow", "raincoat")
127-
```
128-
129-
The call above raises the following exception:
130-
131-
```error
132-
SyntaxError: positional argument follows keyword argument
133-
```
134-
135-
## Functions with Varying Number of Arguments
136-
137-
When defining a function, it may not be necessary to know in advance how many arguments will be needed. In such cases, a special parameter `*args` is passed in. The asterisk, known in this context as the "packing operator", packs the arguments into a [tuple](https://www.codecademy.com/resources/docs/python/tuples) stored in `args`. This tuple can then be iterated through within the function.
138-
139-
In the example below, the `multiply()` function returns the product of all numbers used in the function call.
140-
141-
```py
142-
def multiply(*args):
143-
product = 1
144-
for arg in args:
145-
product *= arg
146-
return product
147-
148-
multiply(21, 24) # Output: 504
149-
multiply(10, 5, 3, 6, 17) # Output: 15300
150-
```
151-
152-
Similarly, functions can be called with an arbitrary number of keyword arguments. In this case, a special parameter `**kwargs` is passed in, where the double asterisk is a packing operator that produces a [dictionary](https://www.codecademy.com/resources/docs/python/dictionaries) rather than a tuple. The parameter name and value of each keyword argument are packed as a key-value pair stored in `kwargs`.
153-
154-
```py
155-
def north_american_capitals(**kwargs):
156-
for country in kwargs:
157-
print(country + ": " + kwargs[country])
158-
159-
north_american_capitals(canada="Ottawa", us="Washington D.C.", mexico="Mexico City")
160-
```
161-
162-
The output of the function call will be:
57+
The resulting output will look like this:
16358

16459
```shell
165-
canada: Ottawa
166-
us: Washington, D.C.
167-
mexico: Mexico City
60+
2018 is not a leap year.
16861
```
16962

170-
When defining a function, both forms of argument packing can be used. However, `args` must always precede `kwargs`.
171-
172-
## Dynamically Passing Arguments
173-
174-
When many arguments need to be passed into a function, it can be tedious to type them out individually. Instead, "argument unpacking" can be used to pass positional or keyword arguments dynamically.
175-
176-
```codebyte/py
177-
def print_biography(name, country, age, hobby):
178-
print("Hello! My name is " + name + " and I'm " + str(age) +
179-
" years old. I come from " + country + ", and in my
180-
free time I like to " + hobby + ".")
181-
182-
adam = {
183-
"name": "Adam",
184-
"country": "Germany",
185-
"age": 23,
186-
"hobby": "paint"
187-
}
188-
189-
print_biography(**adam)
190-
```
191-
192-
## Recursion
193-
194-
Functions in Python can call themselves — a concept known as "recursion". Recursion provides an elegant way to solve problems by breaking them down into smaller, more easily-solvable parts, and using those parts to build up a solution.
195-
196-
Consider the Fibonacci sequence, whose first two terms are explicitly defined to be 0 and 1. Each subsequent term is constructed by taking the sum of the previous two terms. Thus, the first six terms of the sequence are 0, 1, 1, 2, 3, and 5.
197-
198-
Defining a function that prints the `n`-th Fibonacci number is most easily achieved using recursion.
199-
200-
```codebyte/py
201-
def fibonacci(n):
202-
if n <= 1:
203-
# Base cases
204-
return n
205-
else:
206-
# Sum of the previous two terms
207-
return fibonacci(n - 2) + fibonacci(n - 1)
208-
209-
for i in range(6):
210-
print(fibonacci(i))
211-
```
212-
213-
Inside the `else` block of the function definition, two recursive calls to `fibonacci()` (representing the two previous numbers) are added and returned. Once `n` is equal to `0` or `1`, the base case (the `if` block) runs instead.
214-
21563
## Higher-Order Functions
21664

21765
In Python, functions are treated as first-class objects. This means that they can be assigned to variables, stored in data structures, and passed to or returned from other functions.
21866

219-
A function is considered to be of "higher-order" if it takes a function as a parameter or returns a function. One example is the built-in `filter()` function:
67+
Functions are considered to be "higher-order" values because they can be used as parameters or return values for other functions. One example is the built-in `filter()` function:
22068

221-
```py
222-
# Returns true if n is a perfect square, and false otherwise
69+
```codebyte/python
70+
# Returns True if n is a perfect square, and False otherwise
22371
22472
def is_perfect_square(n):
22573
return (n ** 0.5).is_integer()
@@ -229,50 +77,6 @@ numbers = [3, 4, 37, 9, 7, 32, 25, 81, 79, 100]
22977
perfect_squares = filter(is_perfect_square, numbers)
23078
23179
print(list(perfect_squares))
232-
# Output: [4, 9, 25, 81, 100]
23380
```
23481

23582
`filter()` takes a predicate (a function that returns a boolean value) and an iterable, and returns a new iterable containing all elements of the first one that makes the predicate true.
236-
237-
## Anonymous Functions
238-
239-
The act of defining a function using the `def` keyword binds that function to a name. However, some functions can be defined without giving them a name. Such functions are called "anonymous" and are defined using the `lambda` keyword.
240-
241-
```pseudo
242-
lambda <parameters> : <function body>
243-
```
244-
245-
The following two definitions are equivalent.
246-
247-
```py
248-
def add(a, b):
249-
return a + b
250-
```
251-
252-
```py
253-
add = lambda a, b: a + b
254-
```
255-
256-
The expression to the right of the assignment operator is called a "lambda expression". The Python interpreter takes this expression and defines a function object which can be bound to an identifier (in this case, `add`). There is no difference between binding a function to a name using the assignment operator or by using the `def` keyword.
257-
258-
Parameters are optional when defining an anonymous function. However, a function body must be present, and it must only contain a single return expression.
259-
260-
Lambda expressions are most commonly used to define single-use functions which are passed to higher-order functions.
261-
262-
```py
263-
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
264-
265-
odd_numbers = filter(lambda n : n % 2 == 1, numbers)
266-
267-
print(list(odd_numbers))
268-
# Output: [1, 3, 5, 7, 9]
269-
```
270-
271-
Anonymous functions can also be evaluated immediately after they are defined. The expression inside the `print()` function below is known as an "immediately-invoked function expression" (IIFE).
272-
273-
```py
274-
print((lambda a, b: a + b)(1986, 33))
275-
# Output: 2019
276-
```
277-
278-
If the function can be written in a single line, `lambda` could be useful. Otherwise, if the function is more complex, it is recommended to use the `def` keyword.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
---
2+
Title: 'Anonymous Functions'
3+
Description: 'Defines a function without a name using the lambda keyword.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Functions'
9+
- 'Parameters'
10+
- 'Arguments'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/computer-science'
14+
---
15+
16+
The act of defining a function using the `def` keyword binds that function to a name. However, some functions can be defined without giving them a name. Such functions are called "anonymous" and are defined using the [`lambda`](https://www.codecademy.com/resources/docs/python/keywords/lambda) keyword.
17+
18+
```pseudo
19+
lambda <parameter_list> : <function_body>
20+
```
21+
22+
The following two definitions are equivalent.
23+
24+
```py
25+
def add(a, b):
26+
return a + b
27+
28+
29+
add = lambda a, b: a + b
30+
```
31+
32+
The expression to the right of the assignment operator is called a ["lambda expression"](https://www.codecademy.com/resources/docs/python/keywords/lambda). The Python interpreter takes this expression and defines a function object which can be bound to an identifier (in this case, `add`). There is no difference between binding a function to a name using the assignment operator or by using the `def` keyword.
33+
34+
Parameters are optional when defining an anonymous function. However, a function body must be present, and it must only contain a single return expression.
35+
36+
```py
37+
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
38+
39+
odd_numbers = filter(lambda n : n % 2 == 1, numbers)
40+
41+
print(list(odd_numbers))
42+
# Output: [1, 3, 5, 7, 9]
43+
```
44+
45+
Anonymous functions can also be evaluated immediately after they are defined, similar to an immediately-invoked function expression (IIFE) in JavaScript.
46+
47+
```codebyte/python
48+
print((lambda a, b: a + b)(1986, 33))
49+
```
50+
51+
Anonymous functions are useful when the function can be written in a single line. Otherwise, if the function is more complex, it is recommended to use the `def` keyword.

0 commit comments

Comments
 (0)