local variable 'mes' referenced before assignment in python? - python

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

Related

NameError: name 'C' is not defined

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

Why is day_num not defined?

for day_num in range(1,8):
sales=float(input("Enter the sales for Day {}".format(day_num)))
bakery_temp_info.append(sales)
bakery_sale.append(list(bakery_temp_info))
del bakery_temp_info[:]
This is a section of an exemplar code that my teacher gave me. Can anyone explain how the variable "day_num" is used for this loop when it has not been previously defined. I have tried printing it out in the loop and it increases by 1 every time the loop runs. Any help appreciated, thanks.
Python variables don't have to be declared; the first time you assign to one, it's created.
And almost anything that assigns a value to a name counts as an assignment, not just actual = statements. That includes:
name = …
while (name := …) > 0:
for name in …:
import name
with … as name:
def func(name):
… and so on.
Each of these assigns a value to name in the current scope (except for the last one, which only assigns a value in the scope of the function body). It doesn't matter whether name was a variable before that statement or not; it is one now.
If it isn't clear where any assignment is happening, your for loop is equivalent to this while loop:
_range18iter = iter(range(1, 8))
try:
while True:
day_num = next(_range18iter)
# body of the for loop
except StopIteration:
pass
def _range18iter
Now it's obvious that, as long as the iterable is not empty, day_num is going to be assigned to.
You are declaring day_num in the loop. Basically the loop is telling the interpreter that you want to iterate over something and want to give each iteration a name, in this case day_num.
The iterable you are providing in this case is a range from 1-8, but you could just as easily pass it a list. In that case you would be calling each element of the list day_num, as an example.
Every time you run through the loop, it updates the value stored in day_num.

Why does the scope work like this?

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

When is symbol table created in Python

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.

Do you change variables AFTER you run a function in python?

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}

Categories

Resources