Ace
Ace

Reputation: 379

Python: except ValueError only for strings.

Is there a way in Python 3.3 to only except ValueError for strings? If I type a string into k, I want "Could not convert string to float" to be printed, rather than "Cannot take the square root of a negative number."

while True:
    try:
        k = float(input("Number? "))

....

    except ValueError:
        print ("Cannot take the square root of a negative number")
        break
    except ValueError:
        print ("Could not convert string to float")
        break

Upvotes: 1

Views: 6320

Answers (2)

Michael Mauderer
Michael Mauderer

Reputation: 3872

If you want to handle exceptions different depending on their origin, it is best to separate the different code parts that can throw the exceptions. Then you can just put a try/except block around the respective statement that throws the exception, e.g.:

while True:
    try:
        k = float(input("Number? "))
    except ValueError:
        print ("Could not convert string to float")
        break
    try:
        s = math.sqrt(k)
    except ValueError:
        print ("Cannot take the square root of a negative number")
        break

Upvotes: 6

Brendan Long
Brendan Long

Reputation: 54242

Easy, just remove your other except ValueError:

while True:
    try:
        k = float(input("Number? "))

....

    except ValueError:
        print ("Could not convert string to float")
        break

If you want to check if number is negative, just.. check if it's negative:

if k < 0:
   print("Number is negative!")

Upvotes: 1

Related Questions