User Input and Error Handling
Introduction to Scientific Programming with Python
So far, all the values we have assigned to variables have been written directly into our programs. If we want a different value of a variable, we need to edit the code and rerun the program. Of course, this is not how we are used to interacting with computer programs. Usually, a program will receive some input from users, most often through a graphical user interface (GUI). However, although GUIs dominate in modern human-computer interaction, other ways of interacting with computer programs can
... mputer programs can be just as efficient and, in some cases, far more suitable for processing large amounts of data and automating repetitive tasks. In this chapter we will show how we can extend our programs with simple yet powerful systems for user input. In particular, we will see how a program can receive command line arguments when it is run, how to make a program stop and ask for user input, and how a program can read data from files. A side effect of allowing users to interact with programs is that things will often go wrong. Users will often provide the wrong input, and programs should be able to handle such events without simply stopping and writing a cryptic error message to the screen. We will introduce a concept known as exception handling, which is a widespread system for handling errors in programs, used in Python and many other programming languages. Finally, in this chapter, we shall see how to create our own modules that can be imported for use in other programs, just as we have done with the math module in previous chapters.