12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5.11. Keyboard input 455.11 KeyboardinputThe programs we have written so far are a bit rude in the sense that they accept no input from theuser. They justdo the samething every time.<strong>Python</strong>providesabuilt-infunctioncalledraw_inputthatgetsinputfromthekeyboard 1 . Whenthisfunctioniscalled,theprogramstopsandwaitsfortheusertotypesomething. WhentheuserpressesReturnor Enter, theprogram resumes andraw_inputreturns what theuser typed as astring.>>> input = raw_input()What are you waiting for?>>> print inputWhat are you waiting for?Before getting input from the user, it is a good idea to print a prompt telling the user what to input.raw_inputcan take aprompt asan argument:>>> name = raw_input('What...is your name?\n')What...is your name?Arthur, King of the Britons!>>> print nameArthur, King of the Britons!The sequence \n at the end of the prompt represents a newline, which is a special character thatcauses alinebreak. That’s why the user’sinput appears below the prompt.Ifyou expect the user totype aninteger, you can trytoconvert the returnvalue toint:>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'>>> speed = raw_input(prompt)What...is the airspeed velocity of an unladen swallow?17>>> int(speed)17But ifthe user types something other than astringofdigits, you get an error:>>> speed = raw_input(prompt)What...is the airspeed velocity of an unladen swallow?What do you mean, an African or a European swallow?>>> int(speed)ValueError: invalid literal for int()We willseehow tohandle thiskind of error later.5.12 DebuggingThe traceback <strong>Python</strong> displays when an error occurs contains a lot of information, but it can beoverwhelming, especially when there are many frames on the stack. The most useful parts areusually:1 In<strong>Python</strong>3.0, this functionis namedinput.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!