[Tutor] Why can't I make this function work?

Christian Wyglendowski Christian.Wyglendowski at greenville.edu
Thu Jul 15 22:26:51 CEST 2004


> -----Original Message-----
> 
> I have written the following function as part of my guessing 
> game program (as discussed in another thread):
> 
> def Get_int():
>     "Function to collect an integer from the user"
>     type_check = 0
>     while type_check == 0:
>         int = raw_input()

Something to avoid - "int" is a built-in function and type in Python.
By assigning a value to "int" in your funtion, you have overwritten the
built-in in your function's namespace.  Thus, calls to int() from within
your function will not behave as expected.  Which leads us to the next
issue...

>         if type(int) != type(1):
>             print "Invalid input"
> 	else:
> 	    type_check = 1
>     return int

Raw_input() always returns a string.  To get the integer value of a
string, you need to call int() on it - which would present a problem in
your current function with a variable named "int".  After you get your
variable name situation squared away, you'll find that calling int() on
something that can't be converted to an integer raises an exception:

>>> myval = 'this'
>>> int(myval)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ValueError: invalid literal for int(): this


You'll need to implement some exception handling in your function to
deal with this.  Perhaps this example from the interactive interpreter
will get you moving in the right direction:


>>> try: int(myval)
... except ValueError: print 'Not an integer'
... 
Not an integer

> I think the function should keep taking input until an 
> integer is input, at which point it should return the value 
> to the main program.  The function does not cause the program 
> to crash but it doesn't accept any input (returns "Invalid 
> input" whatever I type).  Changing the type_check variable 
> should cause the while loop to exit, shouldn't it?

The loop logic of your function looks good.  You just weren't reaching
the case that would end the loop.

Exceptions...namespaces...weren't you just asking how to fix a simple
function?  :-)  

For more on exceptions, see
http://docs.python.org/tut/node10.html#SECTION0010200000000000000000

If you are curious about namespaces, check out the tutor archives (you
can put this search string into google "namespace tutor
site:mail.python.org").
 
> Thanks for all the help,
> Matt.

I hope it is helpful!

Christian
http://www.dowski.com


More information about the Tutor mailing list