Pass by value or by reference
What a function really receives: a copy or access to the caller's data. Aliases, side effects on a list passed as a parameter, mutable and immutable types, input and output parameters.
- 25 cards
- 7 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
- Line by line
- Step by step
A few cards from the deck
Pass by value: what is it?
Show the answer
A way of passing arguments where the function receives a copy of the argument: changing the parameter changes nothing for the caller.
This is how C works: for a function to change a variable of the caller, you pass it the variable's address.
What does this program print?
```python
def add_one(n):
n = n + 1
return n
x = 5
y = add_one(x)
print(x, y)`5 66 65 56 5
Show the answer
5 6n = n + 1makes the local namenrefer to a new integer, 6:xstill refers to 5. Only the returned value, stored iny, leaves the function.An … parameter is only read by the function; an … parameter lets it pass a result to the caller; an input-output parameter is read then modified.
Show the answer
An input parameter is only read by the function; an output parameter lets it pass a result to the caller; an input-output parameter is read then modified.
In Python, a list passed to a function that sorts it in place is an input-output parameter; an integer can only be an input, and the result comes back through
return.