1

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
4
  • 2
    Why are you having 2 except for ValueError? Commented Nov 8, 2012 at 21:04
  • You're not taking a square root anywhere in the code, so why is that first except ValueError there at all? Commented Nov 8, 2012 at 21:06
  • I am beginner to Python so I may not have done this correctly. I need two separate messages to be printed, one for negative numbers, and one for strings. I am not sure how to do this with one exception. Commented Nov 8, 2012 at 21:08
  • 1
    You could also just print the exception. For a string, you get ValueError: count not convert string to float: 'fdsdfsd'. For a negative number, you get ValueError: math domain error. Commented Nov 8, 2012 at 21:48

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

1

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!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.