 • Print
This chapter is from the book

Getting Numeric Input

As the previous section demonstrated, if you write a program that takes numeric input and does number crunching on it, you need to first convert to a numeric format.

To do that, use one of the following statements, depending on whether you are dealing with integer (int) or floating-point data (float): `var_name = int(input(prompt_message))var_name = float(input(prompt_message))`

These statements combine the input and conversion operations. You can, if you prefer, do them separately, but this is less efficient. For example, you could use this approach:

`in_str = input(’Enter a number: ’)n = int(in_str)`

These two statements work fine together, but there’s no reason not to combine the operations.

`n = int(input(’Enter a number: ’))`

Here’s an interactive session that uses a number entered at the keyboard and then multiplies it by 2:

`>>>def main():    n = int(input(’Enter a number: ’))    print(’Twice of that is:’, n * 2)>>>main()Enter a number: 10Twice of that is: 20`

So, to get actual numeric input, as opposed to storing input in a text string, use the int and float conversions.

But what are int and float, exactly? Here I’m using them like functions, but they’re actually the names of built-in data types, integer and floating point, respectively. In Python, there’s a general rule that type names can be used in this fashion, to perform conversions (assuming the appropriate conversion exists). `type_name(data)`

Example 3.2. Quadratic Formula with I/O

This next example takes the quadratic-formula example another step further, by placing all the statements in a main function and then relying on Python input and output statements to communicate with the end user.

`>>>def main():    a = float(input(’Enter value for a: ’))    b = float(input(’Enter value for b: ’))    c = float(input(’Enter value for c: ’))    determ = (b * b - 4 * a * c) ** 0.5    x1 = (-b + determ) / (2 * a)    x2 = (-b - determ) / (2 * a)    print(’Answers are’, x1, ’and’, x2)>>>main()`

Here is a sample session that might follow after you type main():

`Enter value for a: 1Enter value for b: -1Enter value for c: -1Answers are 1.618033988749895 and -0.6180339887498948`

There are two different answers in this case, not equal to each other, because the golden ratio is either phi (the ratio of the large side to the small) or 1/phi (the ratio of the small side to the large), depending on how you look at it. The negative sign in the second answer is necessary for the math to come out right.

Nearly all the digits are identical in this case, except for a small difference due to rounding errors. The actual values of phi and 1/phi are irrational (which means you would need an infinite number of digits to represent them precisely).