I noticed something really strange while working with functions. It looks like the variable name 'str' is already defined as a global variable. Take a look:
def Example(x):
str = input()
return str
print (Example(str))
#When typing 'Hello!' Output --> Hello!
The variable str is defined in the function Example. So why is there no NameError: name 'str' is not defined?
When I call the variable x or something else ( In this case 'bar'):
def Example(x):
bar = input()
return bar
print (Example(bar))
#Output: NameError: name 'bar'is not defined
Why does a variable with the name 'str' act as a global variable?
In python, str() is the string constructor. It is used to cast an object to a string.
You can use it locally, but it will override the access to the function. You will not be able to use str() anymore.
for reference: https://docs.python.org/2/library/functions.html#str
class str(object='')
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.
For general knowledge purpose, you can get back you constructor if you delete your variable. For example:
test = 1
str(test)
>>>'1'
str = 2
str(test)
>>>TypeError: 'int' object is not callable
del str
str(test)
>>>'1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With