10.4k views
22 votes
You are testing a classmate’s program. The program asks you how many times you want to play the game, and you input “five.” You get the following error message: “ValueError: invalid literal for int() with base 10: 'five.'” What line of code could prevent this problem in the future?

2 Answers

4 votes

Answer:

You put a string into integer value...

Step-by-step explanation:

User Fergaral
by
3.8k points
4 votes

Answer:

The following are totally acceptable in python:

passing a string representation of an integer into int

passing a string representation of a float into float

passing a string representation of an integer into float

passing a float into int

passing an integer into float

But you get a ValueError if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, you can convert to a float first, then to an integer:

>>> int('5')

5

>>> float('5.0')

5.0

>>> float('5')

5.0

>>> int(5.0)

5

>>> float(5)

5.0

>>> int('5.0')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '5.0'

>>> int(float('5.0'))

5

Step-by-step explanation: