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)
CoPoPHP
  • 75
  • 9

1 Answers1

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...
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 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 Apr 10 '14 at 14:22
  • @CoPoPHP just call `getSqrt()` after the try/except block. See I've updated the code in the answer. – alecxe Apr 10 '14 at 14:25
  • @alacxe Should I be getting a Name Error now? `NameError: name 's' is not defined`. I'm not fully understanding this... – CoPoPHP Apr 10 '14 at 14:37
  • @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`: http://stackoverflow.com/questions/8114355/loop-until-a-specific-user-input – alecxe Apr 10 '14 at 14:43
  • @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...". – CoPoPHP Apr 10 '14 at 14:51
  • @CoPoPHP you can also put `getSqrt()` call under `else`. – alecxe Apr 10 '14 at 14:52