tags:

views:

205

answers:

4

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  A: 

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 ...)

weichsel
A: 
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.

Jacob
+5  A: 

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)
Alex Martelli
A: 

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'
Natim
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.
EOL
Ok good to know.
Natim