Today we’ll be talking about numeric data type conversion, and in particular about converting string representations of numbers to numbers.
From user input we get strings into the program:
>>> a = input("What's your name?")
What's your name? Bill
But what if you need a number? For example:
>>> a = input("Enter a number: ")
Enter a number: 42
>>> a # we can print the number
'42'
But you can’t use the number in calculations because technically it’s a string, not a number:
>>> a * 10 # what we get is repetition
'42424242424242424242'
If you want the input to be treated as a number you must cast it to an int or float. You can use the int or float function to achieve that:
>>> x = input("Enter a number: ")
Enter a number: 5
>>> int(x) * 10
50
>>> float(x) + 3.48
8.48
You can cast strings to numbers directly in user’s input:
>>> x = int(input("Enter x: "))
Enter x:
12
>>> y = int(input("Enter y: "))
Enter y:
4
>>> x * y - x
36
Using the eval Function for Type Conversion
We also use the eval function if we need the input to not be treated as a string, but rather as a different data type. For example, we can use it for numbers:
>>> number = eval(input("What's the number?"))
What's the number?
5
Now the input is no longer treated as a string, but as an integer:
>>> type(number)
<class 'int'>
And it can be used in calculations just like any integer:
>>> number * 2
10
Here’s the video version of this article: