A question from a beginner in python. Can someone explain to me /give me a breakdown of the errors here (more than just no declaration in the code):
def a_function(a_parameter):
a_variable = 15
return a_parameter
a_function(10)
print(a_variable)
CodePudding user response:
Let's start line by line
def a_function(a_parameter)
:
This will define a function a_function
which accepts one parameter. Since the default value is not specified, when calling the function a value has to be passed.
a_variable = 15
:
You are declaring a local variable that is defined within the function. You won't be able to call this variable outside the scope of the function.
return(a_parameter)
:
This would return the value of a_parameter, but if you have not specified any value or declared any value for a_parameter when calling the function, you will get an error when you call the function.
a_function(10)
:
This will return the value 10. Since your function is essentially returning the parameter you passed.
print(a_variable)
:
This will give you an error because the a_variable is only accessible within the bounds of the function since it is a local variable.
Hope this helps.
CodePudding user response:
Once a_function
is done running. a_variable
is destroyed and inaccessible. You can reuse the variable name a_variable
.
CodePudding user response:
The variable a_variable
is locally scoped to the function a_function
, i.e. not accessible outside of it. (Python therefore gives you a NameError: name 'a_variable' is not defined
.)
If you want to use a global variable (which is not encouraged), you can use
def a_function(a_parameter):
global a_variable
a_variable = 15
return a_parameter
a_function(10)
print(a_variable)
CodePudding user response:
As a_variable was declared inside a_function, it can be only used inside a_function. If it were declared outside the function, like:
a_variable = 15
def a_function(a_parameter):
print(a_variable)
return a_parameter
a_function(10)
print(a_variable)
It works without raising a NameError and a_variable is accessible inside a_function as well as in any part for the code after it was declared.
Generally variables declared inside functions should only exist for helping the function output its result in order to keep the code organized and without the fear of using a variable that was declared in another function by mistake. If you REALLY want to use A_variable as it is, you could use the global keyword:
def a_function(a_parameter):
global a_variable
a_variable = 15
return a_parameter
a_function(10)
print(a_variable)
To make matters more clear you could read about scope, which your question is all about