Andrei Fortess
Andrei Fortess

Reputation: 23

Why is Python code generating ValueError?

I am writing code that asks the user for any positive integer. If what the user enters is not a positive integer, it must not accept it and ask the user for the positive integer again and again until the user entered a positive integer.

Secondly, the code asks the user for a float between 0 and 1, then checks if what the user entered is a float between 0 and 1. If it is not between 0 and 1, it must ask again, and again until the user entered what is asked for. Then round it up to the nearest 2 decimal place.

Here is my code:

num1 = int(input("Enter a positive integer: "))
while num1 < 0 or not isinstance(num1 , int):
    print("Invalid!")
    num1 = int(input("Enter a positive integer: "))
num2 = float(input("Enter a decimal between 0 and 1: "))
while num2 < 0 or num2 > 1 or not isinstance(num2 , float):
    print("Invalid!")
    num2 = float(input("Enter a decimal between 0 and 1: "))

When I run it, and enter a string, it said ValueError.

Do I have to use error handling?

Upvotes: 1

Views: 271

Answers (2)

enrm
enrm

Reputation: 705

If you try to cast a string in the following way:

>>> text = int("Blibla")

The python interpreter cannot handle it.

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
text = int("Blibla")
ValueError: invalid literal for int() with base 10: 'Blibla'
>>> 

Try instead to use a try/except to catch any ValueErrors :

num1 = 'error'
while not isinstance(num1,int) and num1 == 'error':
    try:
        num1 = int(input("Enter a positive integer: "))
        print("You input : {}".format(num1))
    except ValueError:
        print("Invalid!")

Upvotes: 0

Tamas Hegedus
Tamas Hegedus

Reputation: 29946

ValueError is thrown by the int and float constructor.

while True:
    try:
        num1 = int(input("Enter a positive integer: "))
        if num1 >= 0:
            break
    except ValueError:
        pass
    print("Invalid!")

while True:
    try:
        num2 = float(input("Enter a decimal between 0 and 1: "))
        if num2 >= 0 and num2 <= 1:
            break
    except ValueError:
        pass
    print("Invalid!")

Upvotes: 1

Related Questions