+ 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?

23rd Apr 2023, 4:44 PM
Ratnapal Shende
Ratnapal Shende - avatar
5 Answers
+ 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
23rd Apr 2023, 5:14 PM
Lothar
Lothar - avatar
+ 7
Ratnapal Shende share your code
23rd Apr 2023, 5:00 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
+ 2
Where is your second code that is facing errors??
24th Apr 2023, 12:08 AM
Hasnain [ACTIVE CHALLENGER]
Hasnain [ACTIVE CHALLENGER] - avatar
+ 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
29th Apr 2023, 7:59 AM
Lochard
Lochard - avatar
+ 2
Lochard Thank you so much for your time ! ❀ actually yes you are right 👍 i got confused at that time
29th Apr 2023, 9:13 AM
Ratnapal Shende
Ratnapal Shende - avatar