Suggesting new exercise for the Creating Functions page #248
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The exercise looks at what happens when immutable objects are passed into a function. People without previous programming experience might assume that it's possible to swap 2 numbers using a function written like this. And people with limited programming experience in C or Java (or C-like languages) might see the example code and wonder if, when it comes to primitive types, Python is pass-by-value or pass-by-reference. The answer is that Python is neither. This exercise provides the opportunity to have a discussion about this particular part of the language.
There's a fairly good discussion of how arguments are passed into functions in Python here: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ and the Python docs on how to deal with the problem outlined by this exercise are here: https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
Arguably this exercise introduces new concepts, however, I feel that it is an important "gotcha" to be aware of. The exercise could be seen to build on the discussion in the section titled "Ch-Ch-Ch-Changes" in 03-lists.html by showing how immutable objects behave when passed into a function. The exercise could be extended to get attendees to rewrite the "swap" function so that it will work as intended. An example answer would be: