2

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")
1
  • your and in answers too, cmath.sqrt(y) will give ValueError: math domain error Commented Nov 10, 2009 at 6:48

4 Answers 4

5

The s.isdigit() string method means "string s is one or more characters long and all characters are digits", meaning each character one of 0123456789. 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...:

try:
  thenum = float(y)
except ValueError:
  print "Not a valid number"
else:
  if thenum >= 0:
     x = int(sqrt(thenum))
     print "Answer is", x
  else:
     print "Negative number", cmath.sqrt(thenum)
Sign up to request clarification or add additional context in comments.

Comments

1

your elif never gets evaluated if y is a digit.
The program executes the statements within the if scope and then skips to the last line (raw_input ...)

Comments

0
elif float(y) < 0:
     print "Negative number", cmath.sqrt(float(y))

Now the correct comparison can take place and cmath.sqrt will work since it needs a float.

Comments

0

Why not just :

from math import sqrt
from cmath import sqrt as neg_sqrt

y = raw_input("Enter your number:")
try:
    number = float(y)
    if number > 0:
        print 'Answer is', sqrt(number)
    else:
        print 'Negative number:', neg_sqrt(number)
except ValueError:
    print 'Not a valid number'

1 Comment

The try part is too long: you only want to catch the exception potentially raised by float(). Using else, as in Alex's response, is preferred.

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.