[Tutor] Convert String to Int

Alan Gauld alan.gauld at btinternet.com
Mon Jan 19 10:12:43 CET 2009

"Ian Egland" <echolynx at gmail.com> wrote

> Actually, nobody told me how to catch it before it occurs

x = input('x = ')
if type(x) == int:   # check its an integer
   x = int(x)    # ok, so convert to a number  
   print ("Please enter a number")

But that leads to much more complex and inefficient code
so we prefer

try: x = int(input(...))
except: print ('Please enter a number')

PS. Assuming you are using Python v3. If you are using 
an earlier version its better(safer) to use raw_input() 
rather than input() which is potentially dangerous.
In v3 old style input has been removed and raw_input 
replaced with a new safe input()


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list