简体   繁体   中英

Why inputted float can't be converted to an integer

s=input('what is your name\n')
l=int(input('how old are you?\n'))
print('you are',s,l,'years old')

When I assign 13 to l it works, but when I assign 13.5 I get:

l=int(input('how old are you?\n'))
ValueError: invalid literal for int() with base 10: '13.5'

Why is that?

It's not a float, it's a string, '13.5' . input() does not evaluate what you input. To be clear, int('13.5') is not valid.

If you want to allow float inputs, you'll need to handle them somehow, for example:

Use decimal instead

import decimal
age = decimal.Decimal(input(...))
>>> age = decimal.Decimal('13')
>>> age
Decimal('13')
>>> print(age)
13
>>> age = decimal.Decimal('13.5')
>>> age
Decimal('13.5')
>>> print()
13.5

Truncate

age = int(float(input(...)))
>>> int(float('13'))
13
>>> int(float('13.5'))
13

Round

age = round(float(input(...)))
>>> round(float('13'))
13
>>> round(float('13.5'))
14
>>> round(float('12.5'))  # Python uses banker's rounding
12

Use all floats

age = float(input(...))
>>> float('13')
13.0
>>> float('13.5')
13.5

In any case, you should use a try-except to catch invalid input, including invalid numbers like foobar and the exotic real numbers: inf , -inf , nan , and -0 . See Asking the user for input until they give a valid response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM