Home > Articles

  • Print
  • + Share This
This chapter is from the book

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)

Enter a number: 10
Twice 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).


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)


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

Enter value for a: 1
Enter value for b: -1
Enter value for c: -1
Answers 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).

  • + Share This
  • 🔖 Save To Your Account