1

I'm trying to implement the try...except exception handling into the code below. When something like "s4" is entered, I want the output of "Non numeral value..." to appear.

Any idea on where I've gone wrong?

import string

import math

def getSqrt(n):
    return math.sqrt(float(n))

s = input("Enter a numerical value: ")

try:
    for i in s:
        if (i.isdigit() or i == "."):
            sType = "nonstr"

    if (sType =="nonstr"):
        print(getSqrt(s))

    else:
        s = "Non numberical value..."


except ValueError as ex:
    print(ex)


else:
    print(s)
2
  • 1
    you need to check your nonstr condition again. Commented Apr 10, 2014 at 14:09
  • 1
    also, if you are testing the string already, what exception do you expect? Commented Apr 10, 2014 at 14:09

1 Answer 1

5

Ask for forgiveness - convert the entered value to float and handle ValueError:

try:
    s = float(input("Enter a numerical value: "))
except ValueError:
    print("Non numberrical value...")
else:
    print(getSqrt(s))

Demo:

>>> try:
...     s = float(input("Enter a numerical value: "))
... except ValueError:
...     print("Non numberrical value...")
... 
Enter a numerical value: s4
Non numberrical value...
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the feedback. Excuse my confusion, but how do I implement this into the code above to still handle when an integer is entered and the square root is returned? I shoud have explained ths further in my initial question.
@CoPoPHP just call getSqrt() after the try/except block. See I've updated the code in the answer.
@alacxe Should I be getting a Name Error now? NameError: name 's' is not defined. I'm not fully understanding this...
@CoPoPHP well, it depends on what are you planning to do on error. You can exit the program by calling sys.exit() or you can allow the user to enter the number again until there wouldn't be a ValueError: stackoverflow.com/questions/8114355/…
@alacxe Thanks, let me take a look at the link. Basically, I'm trying to either display the square root or the "Non numerical value...".
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.