This is my code snippet, but it not execute the way that I want.The first if statement executes successfully if the input is a non-negative/character value, but if it is a negative value it ignores the elif statement. What’s the issue.I’m using Python 2.6
from math import sqrt
import cmath
y = raw_input("Enter your number:")
if y.isdigit():
x = int(sqrt(float(y)))
print "Answer is", x
elif y < 0:
print "Negative number", cmath.sqrt(y)
else:
print "Not a valid number"
raw_input("Press <enter> to Exit")
The
s.isdigit()string method means “stringsis one or more characters long and all characters are digits”, meaning each character one of0123456789. Note how other characters such as+and-are signally absent from that set;-).Your
elif y < 0:test is applied to a string y and therefore is nonsensical. If you want to check if what the user entered is a number, the right approach is really totally different from what you have…: