+ 2
[Closed ]Error in interpreter but not in script mode why ?
sum = 1+2 print(sum) above code prints 3 in script mode but in interactive mode it gives object of sum built-in function why this unexpected behaviour happens? where is LEGB rule of resolving names in interactive mode?
5 Réponses
+ 9
Ratnapal Shende ,
without having seen your code it is difficult to guess what exactly happens, but a part of the problem can be the use of *reserved python keywords*.
>>> please avoid using reserved names from built-in functions or other objects when creating codes.
keywords that are frequently used as variable names:
id, list, dict, input, *sum*, min, max, ... <= these are all reserved keywords in python
>>> this can lead to a unexpected behavior or to an error. the reason is (if we use reserved words), that the corresponding built-in function or object
can be shadowed or will be overwritten.
> in pep 8 - (style guide for python code) we can find this in section:
> descriptive: naming styles :
single_trailing_underscore_ : ***used by convention to avoid conflicts with python keywords***
e.g.: sum_ = result1 + result2
+ 7
Ratnapal Shende share your code
+ 2
Where is your second code that is facing errors??
+ 2
Just like others and you have mentioned, there is a built-in function called sum.
But I am not able to reproduce the behaviour you described. The int variable declaration always shadows the built-in function no matter which mode it is.
I have tried on replit and my own terminal. Here is a screenshot of first running the script file and then repeat the same in interactive mode.
https://raw.githubusercontent.com/locharp/assets/main/jpg/JUMP_LINK__&&__python__&&__JUMP_LINK-print-sum.jpg
+ 2
Lochard Thank you so much for your time ! ❤️
actually yes you are right 👍
i got confused at that time