2011 | OriginalPaper | Buchkapitel
Input Data and Error Handling
verfasst von : Hans Petter Langtangen
Erschienen in: A Primer on Scientific Programming with Python
Verlag: Springer Berlin Heidelberg
Aktivieren Sie unsere intelligente Suche, um passende Fachinhalte oder Patente zu finden.
Wählen Sie Textabschnitte aus um mit Künstlicher Intelligenz passenden Patente zu finden. powered by
Markieren Sie Textabschnitte, um KI-gestützt weitere passende Inhalte zu finden. powered by
Recall our first program for evaluating the formula (1.2) on page 19 in Chapter 1:
C = 21
F = (9/5)*C + 32
print F
In this program,
C
is input data in the sense that
C
must be known before the program can perform the calculation of
F
. The results produced by the program, here
F
, constitute the output data.
Input data can be hardcoded in the program as we do above. That is, we explicitly set variables to specific values (
C = 21
). This programming style may be suitable for small programs. In general, however, it is considered good practice to let a user of the program provide input data when the program is running. There is then no need to modify the program itself when a new set of input data is to be explored.
This chapter starts with describing three different ways of reading data into a program: (i) letting the user answer questions in a dialog in the terminal window (Chapter 4.1), (ii) letting the user provide input on the command line (Chapter 4.2), and (iii) letting the user write input data in a graphical interface (Chapter 4.4). A fourth method is to read data from a file, but this topic is left for Chapter 6.
Even if your program works perfectly, wrong input data from the user may cause the program to produce wrong answers or even crash. Checking that the input data are correct is important, and Chapter 4.3 tells you how to do this with so-called exceptions.
The Python programming environment is organized as a big collection of modules. Organizing your own Python software in terms of modules is therefore a natural and wise thing to do. Chapter 4.5 tells you how easy it is to make your own modules.
All the program examples from the present chapter are available in files in the
src/input
folder.