Python if else condition error

10,599

Solution 1

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)

Solution 2

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

Share:
10,599
Switch
Author by

Switch

enter link description here

Updated on June 04, 2022

Comments

  • Switch
    Switch almost 2 years

    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")
    
  • Bruno Feroleto
    Bruno Feroleto over 14 years
    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.