06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

46 Conditionals and recursion<br />

>>> name = raw_input ("What...is your name? ")<br />

What...is your name? Arthur, King of the Bri<strong>to</strong>ns!<br />

>>> print name<br />

Arthur, King of the Bri<strong>to</strong>ns!<br />

If we expect the response <strong>to</strong> be an integer, we can use the input function:<br />

prompt = "What...is the airspeed velocity of an unladen swallow?\n"<br />

speed = input(prompt)<br />

The sequence \n at the end of the string represents a newline, so the user’s input<br />

appears below the prompt.<br />

If the user types a string of digits, it is converted <strong>to</strong> an integer and assigned <strong>to</strong><br />

speed. Unfortunately, if the user types a character that is not a digit, the program<br />

crashes:<br />

>>> speed = input (prompt)<br />

What...is the airspeed velocity of an unladen swallow?<br />

What do you mean, an African or a European swallow?<br />

SyntaxError: invalid syntax<br />

To avoid this kind of error, it is generally a good idea <strong>to</strong> use raw input <strong>to</strong> get a<br />

string and then use conversion functions <strong>to</strong> convert <strong>to</strong> other types.<br />

4.13 Glossary<br />

modulus opera<strong>to</strong>r: An opera<strong>to</strong>r, denoted <strong>with</strong> a percent sign (%), that works on<br />

integers and yields the remainder when one number is divided by another.<br />

boolean expression: An expression that is either true or false.<br />

comparison opera<strong>to</strong>r: One of the opera<strong>to</strong>rs that compares two values: ==, !=,<br />

>, =, and

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

Saved successfully!

Ooh no, something went wrong!