Can anyone tell me, why C is not defined?
I expect an output in the end for C.
Here c is not defined because c is a local variable that can be assessed only inside taxes function.
You can try the below code :
c = taxes(x)
In this way, you assign the value 1000 or whatever your function return to c. And your code won't give an error
Related
I'm working on this function that converts a Julian day to a gregorian date, the output should look like ex. 22.0,12.0,2000 thats why in print I have those three variables, but when I run it, it gives me the error:
local variable 'mes' referenced before assignment.
Also, "A" appears to be highlighted in yellow with the warning "local variable A might be referenced before assignment". I don't know how to fix it.
I've tried changing the indentation, but I don't see what's wrong.
Below is my function:
def JD2fechaGregoriana(fecha):
fecha1=int(fecha+0.5)
fecha2=float(fecha1-fecha)
Z =fecha1
F = fecha2
if (Z<2299161):
A=Z
elif (Z>= 2291161):
alpha=int((Z-1867216.25)/36524.25)
A= Z + 1 + alpha -int(alpha/4)
B= A +1524
C= int((B-122.1)/365.25)
D= int(365.25*C)
E= int((B-D)/30.6001)
dia1= B-D - int(30.6001*E)+F
if (E>14):
mes=E-1
elif (E==14 or E==15):
mes=E-13
if (mes>2):
anio=C-4716
elif(mes==1 or mes==2):
anio=C-4715
print(dia1,mes,anio)
Thank you in advance.
You are using variable mes in an if...else and then printing its value.
Even though variable mes exists, you are assigning its value inside if...else block, naturally this will create variable inside the if block, and therefore when you try to print mes it gives the error:
You should first declare variable as 0 before if statement, and then further use this in if block.
eg:
.....
mes=0
if (E>14):
mes=E-1
......
And same goes with variable A.
It would work!
Friend, review the topic of the scope of the variables, declare the variables before comparing them in IF -ELSE. Initialize them with some value. For example
month = 0
A = 0
Hello Stack Overflow Community,
I am trying to write a program that checks Fermat's Last Theorem. The issue I am running into is that an error appears saying "NameError: name 'a' is not defined. However, I define 'a' in my first function and return its value at the end of the function.
I am trying to use the inputed values from the first function in the second function so the user can define the parameters.
Am I misunderstanding how to leverage "Return"? All help is greatly appreciate and will keep me sane.
def input_fermat():
a=input('Enter the first variable \'a\': \n')
b=input('Enter the second variable \'b\': \n')
c=input('Enter the third variable \'c\': \n')
n=input('Enter the exponential variable \'n\': \n')
return a, b, c, n
def check_fermat(a,b,c,n):
calc_1=a**n
calc_2=b**n
calc_3=c**n
if n>2 and int(calc_1) + int(calc_2) == calc_3:
print('Holy smokes, Fermat was wrong!')
else:
print('No that doesn\'t work.')
input_fermat()
check_fermat(a,b,c,n)
The variables a, b, c, n defined in input_fermat only exists within the function, that's why you return them, but when you call the function you aren't saving them anywhere. You should replace:
input_fermat()
By:
a, b, c, n = input_fermat()
Or you can directly pass the return value of input_fermat to check_fermat like this:
check_fermat(*input_fermat())
You are not storing the values that the function input_fermat returns. Try:
a, b, c, n = input_fermat()
check_fermat(a,b,c,n)
This is happening because those variables are defined locally and are not available in check_fermat's namespace.
Refer to the LEGB-rule.
What you can do is define all of those variables using the global keyword in the function definition, although this isn't usually the best approach. You'll also want to cast all of your inputs to ints since input() will return a string.
Returned values don't just automatically show up in your namespace, you have to assign them to something.
a, b, c, n = input_fermat()
Variables a,b,c and n, which you receive as input in input_fermat(), are only available within the body of that function; once you return, you're out of input_fermat()'s scope and the values in a,b,c and n are handed off to whatever variables you called input_fermat() to assign .
A function's scope means the only variables available in any given function are
those that are declared in the body of the function
those passed to the function as arguments in parentheses.
variables declared globally
In check_fermat(),this means you could re-use variables a,b,c and for something other than the input, if you wanted (because a new function means a new scope).
But, in the code shown below, we decide that a,b,c and n in check_fermat() are going to be the same thing as a,b,c and d in input_fermat() with the declaration a,b,c,n = input_fermat(). This is a decision we chose to make; it's arbitrary.
Here's an edited version of your function that accomplishes what I think you were going for:
#Global variables would be declared up here, before all other function declarations.
#Global variables would be available to all the functions that follow.
def input_fermat(): #if there were arguments in these parentheses they'd be included in input_fermat scope
# input_fermat() scope begins
a=int(input('Enter the first variable \'a\': \n'))
b=int(input('Enter the second variable \'b\': \n'))
c=int(input('Enter the third variable \'c\': \n'))
n=int(input('Enter the exponential variable \'n\': \n'))
return a, b, c, n
#input_fermat() scope ends
def check_fermat(): #if there were arguments in these parentheses they'd be included in check_fermat scope
#check_fermat() scope begins
#just as you returned 4 variables at once in input_fermat(), 4 variables can be assigned at once here
a,b,c,n = input_fermat() #need to assign because a, b, c, n from input_fermat() no longer in scope
calc_1=a**n
calc_2=b**n
calc_3=c**n
if n>2 and int(calc_1) + int(calc_2) == calc_3:
print('Holy smokes, Fermat was wrong!')
else:
print('No that doesn\'t')
#python implicitly does a `return None` here
#check_fermat() scope ends
check_fermat()
Note that because of the scopes of these functions, I could have declared the variables in check_fermat() as follows and it would all still work (try running this code for yourself to see)
def input_fermat():
a=int(input('Enter the first variable \'a\': \n'))
b=int(input('Enter the second variable \'b\': \n'))
c=int(input('Enter the third variable \'c\': \n'))
n=int(input('Enter the exponential variable \'n\': \n'))
return a, b, c, n
def check_fermat():
any,variable,names,go = input_fermat()
calc_1=any**go
calc_2=variable**go
calc_3=name**go
if n>2 and int(calc_1) + int(calc_2) == calc_3:
print('Holy smokes, Fermat was wrong!')
else:
print('No that doesn\'t')
check_fermat()
The Process of execution (for both code snippets) goes like this:
check_fermat() on the last line is executed because it's the only function called (not just defined) in our .py file.
Python looks for the definition of check_fermat() to execute it
3.Python finds input_fermat() is called inside check_fermat and goes looking for input_fermat()s definition.
Python finds the definition, executes the function and asks for input.
Input is returned back to check_fermat() and is used to compute Fermat's Last Theorem.
The rest of check_fermat() is carried out (output is printed to terminal). Then, check_fermat() returns None, ending the function call with no variables to return.
This question is a result of a student of mine asking a question about the following code, and I'm honestly completely stumped. Any help would be appreciated.
When I run this code:
#test 2
a = 1
def func2(x):
x = x + a
return(x)
print(func2(3))
it works perfectly fine. It is able to take the globally-scoped variable a and use its value to perform the calculation and return the value 4.
However, if I change it to this:
# test 3
a = 1
def func3(x):
a = x + a
return(x)
print(func3(3))
I then get an error:
local variable 'a' referenced before assignment
Why do I get this error only when I want to update the value of a within the function to a new value based on its original value? What am I not understanding? I feel like this second piece of code should work fine.
Thanks in advance for any help and insight.
a = 1
def func3(x):
global a
a = x + a
return(x)
print(func3(3))
Now it should work.
When you put the statement a=x+a inside the function, it creates a new local variable a and tries to reference its value(which clearly hasnt been defined before). Thus you have to use global a before altering the value of a global variable so that it knows which value to refer to.
EDIT:
The execution of a function introduces a new symbol table used for the
local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the local symbol tables of enclosing functions, then in the global
symbol table, and finally in the table of built-in names. Thus, global
variables cannot be directly assigned a value within a function
(unless named in a global statement), although they may be referenced.
def func3(x):
a = x + a
return(x)
On the right hand right side of a = x + a (So, x + a), 'x' is passed as variable, where 'a' is not passed as a variable thus an error.
Without using globals:
a = 1
def func3(x, a=2):
a = x + a
return(x)
func3(3)
Returns: 5
def square():
print(a)
a = 10
b = a*a
return b
a = 2
print(square())
UnboundLocalError: local variable 'a' referenced before assignment
def square():
print(a)
#a = 10
b = a*a
return b
a = 2
print(square())
I just want to make sure why the second scenario is right while the first is wrong.
The execution of a function introduces a new symbol table used for the
local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the local symbol tables of enclosing functions, then in the global
symbol table, and finally in the table of built-in names.
While interpreter is going through the definition of the function it creates a symbol table. It first thinks 'a' as global(due to print(a)) and later creates 'a' in local symbol table(Due to assignment).
So while actually executing the function, 'a' is a local which has no binding. Hence the error.
Is my reasoning right about symbol tables??
Update: Adding global after assignment:
def square():
print(a)
a = 10
b = a*a
global a
return b
a = 2
print(square())
print(a)
Does global a statement remove name 'a' from the local symbol table of square function?
It's a scope issue. Check this answer : https://stackoverflow.com/a/293097/1741450
Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope.
The first example is wrong since a cannot be modified.
So I wrote this function from a book I am reading, and this is how it starts:
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
ok, makes sense. and then, this is when this function is run where I got a little confused and wanted to confirm something:
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
the thing that confused me here is that the amount_of_cheese and amount_of_crackers is changing the variables (verbage? not sure if i am saying the right lingo) from cheese_count and boxes_of_crackers repectively from the first inital variable labels in the function.
so my question is, when you are using a different variable from the one that is used in the initial function you wrote, why would you change the name of the AFTER you wrote out the new variable names? how would the program know what the new variables are if it is shown after it?
i thought python reads programs top to bottom, or does it do it bottom to top?
does that make sense? i'm not sure how to explain it. thank you for any help. :)
(python 2.7)
I think you are just a bit confused on the naming rules for parameter passing.
Consider:
def foo(a, b):
print a
print b
and you can call foo as follows:
x = 1
y = 2
foo(x, y)
and you'll see:
1
2
The variable names of the arguments (a, b) in the function signature (1st line of function definition) do not have to agree with the actual variable names used when you invoke the function.
Think of it as this, when you call:
foo(x, y)
It's saying: "invoke the function foo; pass x in as a, pass y in as b". Furthermore, the arguments here are passed in as copies, so if you were to modify them inside the function, it won't change the values outside of the function, from where it was invoked. Consider the following:
def bar(a, b):
a = a + 1
b = b + 2
print a
x = 0
y = 0
bar(x, y)
print x
print y
and you'll see:
1
2
0
0
The script runs from top to bottom. The function executes when you call it, not when you define it.
I'd suggest trying to understand concepts like variables and function argument passing first.
def change(variable):
print variable
var1 = 1
change(var1)
In the above example, var1 is a variable in the main thread of execution.
When you call a function like change(), the scope changes. Variables you declared outside that function cease to exist so long as you're still in the function's scope. However, if you pass it an argument, such as var1, then you can use that value inside your function, by the name you give it in the function declaration: in this case, variable. But it is entirely separate from var! The value is the same, but it is a different variable!
Your question relates to function parameter transfer.
There are two types of parameter transfer into a function:
By value ------- value changed in function domain but not global domain
By reference ------- value changed in global domain
In python, non-atomic types are transferred by reference; atomic types (like string, integer) is transferred by value.
For example,
Case 1:
x = 20
def foo(x):
x+=10
foo()
print x // 20, rather than 30
Case 2:
d = {}
def foo(x): x['key']=20
foo(d)
print d // {'key': 20}