[Tutor] Who uses input()? [was Re: question on "input"]

Brian van den Broek bvande at po-box.mcgill.ca
Mon Jul 18 19:54:22 CEST 2005

Nathan Pinno said unto the world upon 2005-07-18 09:36:
>   Danny,
>   It sure did, though I wish there was an easier way of coding it than 
> int(raw_input())! Any ideas would gladly be appreciated.

<snip second question>

>   Thanks,
>   Nathan Pinno.

<snip Danny's explanation why use of input for 'private code' can 
still be dangerous>

Hi Nathan,

If you find it irritating to type int(raw_input()), just wrap it all 
into a function. The minimal thing would be:

 >>> def get_int(prompt):
	return int(raw_input(prompt))

But, if you are doing that, might as well make the function do a bit more:

 >>> def get_int(prompt):
	if not prompt.endswith('\n'):
		prompt += '\n'
	while True:
			temp = raw_input(prompt)
			return int(temp)
		except ValueError:
			print "'%s' is not an integer. Please try again.\n" %temp

 >>> a = get_int('I wanna number!')
I wanna number!
OK, one.
'OK, one.' is not an integer. Please try again.

I wanna number!
 >>> a

If you make such a function, test it well, make it general, etc., then 
you can put it into your own user_input module and never have to write 
either int(raw_input) or input checking code again. (I've done 
something like this, with extra things like making sure prompt is an 
appropriate type of object, etc. Notice what happens as it is now if 
you do get_int(757575).)


Brian vdB

More information about the Tutor mailing list