[Tutor] Is input a Python function or command?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 1 20:21:23 CEST 2005



> Thanks Luke. Saved me quite a headache. I will use in_file instead.
> Makes more sense anyway.


Hi Nathan,

Just wanted to chime in here: you may have fewer issues with name
conflicts if you use more functions.

For example:

######
>>> def test():
...     input = 42
...     print input
...
>>> test()
42
>>> input
<built-in function input>
######


What this tries to so is that functions offer a little bit of isolation:
within a function, you can usually just use names with abandon, because it
won't affect the outside world.  We'd say here that test() uses 'input' as
a "local" variable.


Of course, if we try to do something like:

######
>>> def test():
...     input = 42
...     s = input("hi, what's your age? ")
...
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in test
TypeError: 'int' object is not callable
######

we should expect to see trouble within the function, since we've
overwritten 'input'.


However, outside the function, we're still good:

######
>>> input("hello: ")
hello: 42
42
######


So that's one benefit of doing work in functions: we can box things in so
that, if we make a mistake, our mistake is isolated to the function, and
not to the outside world.


Hope this helps!



More information about the Tutor mailing list