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.

126 Files and exceptions<br />

if x == 17 :<br />

raise ValueError, ’17 is a bad number’<br />

return x<br />

The raise statement takes two arguments: the exception type and specific information<br />

about the error. ValueError is one of the exception types <strong>Python</strong> provides<br />

for a variety of occasions. Other examples include TypeError, KeyError, andmy<br />

favorite, NotImplementedError.<br />

If the function that called inputNumber handles the error, then the program can<br />

continue; otherwise, <strong>Python</strong> prints the error message and exits:<br />

>>> inputNumber ()<br />

Pick a number: 17<br />

ValueError: 17 is a bad number<br />

The error message includes the exception type and the additional information you<br />

provided.<br />

As an exercise, write a function that uses inputNumber <strong>to</strong> input a<br />

number from the keyboard and that handles the ValueError exception.<br />

11.6 Glossary<br />

file: A named entity, usually s<strong>to</strong>red on a hard drive, floppy disk, or CD-ROM,<br />

that contains a stream of characters.<br />

direc<strong>to</strong>ry: A named collection of files, also called a folder.<br />

path: A sequence of direc<strong>to</strong>ry names that specifies the exact location of a file.<br />

text file: A file that contains printable characters organized in<strong>to</strong> lines separated<br />

by newline characters.<br />

break statement: A statement that causes the flow of execution <strong>to</strong> exit a loop.<br />

continue statement: A statement that causes the current iteration of a loop<br />

<strong>to</strong> end. The flow of execution goes <strong>to</strong> the <strong>to</strong>p of the loop, evaluates the<br />

condition, and proceeds accordingly.<br />

format opera<strong>to</strong>r: The % opera<strong>to</strong>r takes a format string and a tuple of expressions<br />

and yields a string that includes the expressions, formatted according<br />

<strong>to</strong> the format string.<br />

format string: A string that contains printable characters and format sequences<br />

that indicate how <strong>to</strong> format values.

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

Saved successfully!

Ooh no, something went wrong!