# eval() vs. float() vs. int()¶

The use of the eval() function is tricky. We abuse it for our creative educational use, but it should not be used wantonly in your code. A better method is to convert the text entered directly into the data type you expect. Are you asking the user for an integer? Convert the returned value using int(), or if a float is wanted use float(). They fail predictably and allow you to catch the errors robustly (we'll learn about exceptions soon).

In [1]:
num = eval(input("Enter a number, as an integer: "))

Enter a number, as an integer: 90

In [2]:
print(num)

90

In [3]:
num = eval(input("Enter a number, as an integer: "))

Enter a number, as an integer: 89.33

In [4]:
print(num)

89.33

In [5]:
num = int(input("Enter a number, as an integer: "))

Enter a number, as an integer: 90

In [6]:
print(num)

90

In [7]:
num = int(input("Enter a number, as an integer: "))

Enter a number, as an integer: 89.33

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-814b9ef51fab> in <module>()
----> 1 num = int(input("Enter a number, as an integer: "))

ValueError: invalid literal for int() with base 10: '89.33'
In [8]:
num = float(input("Enter a number, as a float: "))

Enter a number, as a float: 90

In [9]:
print(num)

90.0

In [10]:
num = float(input("Enter a number, as a float: "))

Enter a number, as a float: 89.33

In [11]:
print(num)

89.33

In [12]:
float(1)

Out[12]:
1.0
In [13]:
int(2.3)

Out[13]:
2
In [15]:
int("2.3")

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-5ed61bf3052f> in <module>()
----> 1 int("2.3")

ValueError: invalid literal for int() with base 10: '2.3'
In [19]:
"This float, {0:10.5f}, is fixed at 5 decimal places".format(3.1415926)

Out[19]:
'This float,    3.14159, is fixed at 5 decimal places'