0
Python code
def foo(): total +=1 return total total = 0 print(foo()) Why is this code wrong and can anyone explain this code in every step, also what is this foo ?
6 Respostas
+ 4
rajul , i can not recommend to use global varibales in most cases. There may be some exceptions to use them, but in most cases it is much more cleaner to go an other way. Global varibales have no protection, means that from where ever in your code they can be modified. This looks promising at the first glance, but it can have some bad side effects, if the modification is done by accident. A code using global varibales is more difficult to maintain, and debugging can be a real nightmare.
So here is a way you can go instaed of using globals:
def foo(total_):
return total_ +1
total = 0
print(foo(total))
+ 1
You should declare 'total' variable before the function
0
def foo():
total +=1 #total is not defined yet. Global outside declared total is different and not availablein functions so you must define it before using
return total
total = 0
print(foo())
Solution :
def foo():
global total #telling interpreter to use global total..
total +=1 #now its fine
return total
total = 0
print(foo())
0
Mirielle[ InAcTiVe ] Ok thanks