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 ?

19th Sep 2020, 4:51 PM
rajul
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))
19th Sep 2020, 7:05 PM
Lothar
Lothar - avatar
+ 1
You should declare 'total' variable before the function
20th Sep 2020, 5:43 AM
Arshia
Arshia - avatar
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())
19th Sep 2020, 5:04 PM
Jayakrishna 🇮🇳
0
Mirielle[ InAcTiVe ] Ok thanks
19th Sep 2020, 5:13 PM
Rice Noodle
Rice Noodle - avatar