[Tutor] Function not returning 05 as string

Peter Otten __peter__ at web.de
Mon Apr 13 14:44:09 CEST 2015


Ken G. wrote:

> I am sure there is an simple explanation but when I input
> 5 (as integer), resulting in 05 (as string), I get zero as the end
> result. When running the code:
> 
> START OF PROGRAM:
> Enter the 1st number:  5
> 
> 05
> 
> 0
> END OF PROGRAM:
> 
> START OF CODE:
> import sys
> 
> def numberentry():
>      print
>      number01 = raw_input("Enter the 1st number:  ")
>      if number01 == "0":
>          sys.exit()
>      if  len(number01) == 1:
>          number01 = "0" + number01
>      print
>      print number01
>      return(number01)
> 
> number01 = 0
> numberentry()
> print
> print number01
> END OF CODE:

Let's simplify that and run it in the interactive interpreter:

>>> x = 0
>>> def f():
...     x = 5
...     print x
... 
>>> f()
5
>>> x
0

You are seeing two different values because there are two separate 
namespaces. The x = 0 lives in the "global" namespace of the module while 
the other x = 5 exists in the "local" namespace of the function, is only 
visible from a specific invocation of f() and only while that specific 
invocation of f() is executed.

If you want see the value of a global variable from within a function you 
must not rebind it:

>>> def g():
...     print x
... 
>>> f()
5
>>> x = 42
>>> f()
5

If you want to update a global variable you should do that explicitly

>>> def h():
...     return "foo"
... 
>>> x = h()
>>> x
'foo'

but there is also the option to declare it as global inside the function:

>>> def k():
...     global x
...     x = "bar"
... 
>>> k()
>>> x
'bar'

The global keyword is generally overused by newbies and tends to make your 
programs hard to maintain.

Try it a few times to ensure that you understand how it works -- and then 
forget about it and never use it again ;)

Back to your original code -- assuming that you want to update the global 
name 'number01' you could rewrite it like this:


def numberentry():
     digit = raw_input("Enter the 1st number:  ")
     if len(digit) != 1 or not digit.isdigit():
         raise ValueError("Not an allowed input: {!r}".format(digit))
     return digit.zfill(2)

number01 = numberentry()
if number01 != "00":
    print number01




More information about the Tutor mailing list