Keyboard Input

Reading data from the keyboard is very different from reading data from a file. Files exist before being read, and normally have a fixed size that is known in advance. It is common to know the format of a file, so that the fact that the next datum is an integer and the one following that is a float is often known. When a user is entering data at a keyboard, there is no such information available. In fact, the user may be making up the data as they go along. Before getting too far into file input, it is important to understand the kind of errors that can happen interactively.

These are using type errors, where the user enters data that is the wrong type for the programmer to use: a string instead of an integer, for example. This kind of error can arise in file input if the format is not known in advance.

1. Problem: Read a number from the keyboard and divide it by 2

This problem addresses how to treat integers like integers and floats like floats. When the string s is read in, it is just a string, and it is supposed to contain an integer. However, users will be users, and some may type in a float by mistake. The program should not crash just because of a simple input mistake. How is this situation handled?

The problem is that when the string is converted into an integer, if there is a decimal point or other non-digit character that does not belong then an error will occur. It seems that an answer would be to put the conversion into a try state­ment block and if the string has a decimal point, then convert the string to a float within the except part. The code looks like this:

s = input(“Input an integer: “)

try:

k = int(s)

ks = k

//2 except:

z = float(s)

k = int(z/2)

print (k)

If the user types “12” in response to the prompt “Input an integer:,” then the program prints “6.” If the user types “12.5,” then the program catches a ValueEr- ror, because 12.5 is not a legal integer. The except part is executed, converting the number to floating point, dividing by 2, then finally converting to an integer.

One problem is that the except part is not part of the try, so errors that hap­pen there will not be caught. Imagine that the user types “one” in response to the prompt. The call to int(s) results in a ValueError, and the except part is executed. The statement

z = float(s)

results in another ValueError. This one will not be caught and the program will stop executing, giving a message like:

ValueError: could not convert string to float:    ‘one’

s = input(“Input an integer:  “)

try:

k = int(s)

k = k//2

except ValueError:

try:

z = float(s)

k = int(z/2)

except ValueError:

k = 0

print (s, k)

 

Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *