Last active
October 25, 2021 16:49
-
-
Save ryanorsinger/4ca7a3f73be63d28d678273951c3513f to your computer and use it in GitHub Desktop.
Critical difference between global variables and function parameters and local variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Consider the following | |
# This global variable is defined outside the scope of all functions | |
global_variable = 1 | |
# The parameter is the "input variable". Calling the function "sends in" a value, assigning it to parameter_variable | |
# The scope of the parameter variable is only inside of a function | |
def add_one(parameter_variable): | |
return global_variable + 1 | |
# This works because the global_variable + 1 is 2 | |
print("The input argument is 1. One plus one is two. add_one(1) returns", add_one(1)) | |
# This fails because the function is returning global_variable + 1. | |
print("The input argument is 2. Two plus one is three. add_one(2) returns,", add_one(2)) | |
# This fails because the function is returning global_variable + 1 and argument is 100. | |
# 100 + 1 should be 101 | |
print("The input argument is 100. One hundred plus one is a hundred and one. add_one(100) returns", add_one(100)) | |
print() | |
# An appropriate add_one function depends on the input argument and is correct, predictable, and reusable. | |
def correct_add_one(parameter_variable): | |
return parameter_variable + 1 | |
print("The input argument is 1. One plus one is two. correct_add_one(1) returns", correct_add_one(1)) | |
print("The input argument is 2. Two plus one is three. correct_add_one(2) returns,", correct_add_one(2)) | |
print("The input argument is 100. One hundred plus one is a hundred and one. correct_add_one(100) returns", correct_add_one(100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment