If elif problem. elif doesn't work, but no error


#1

name=raw_input("What’s your name? ")

print “Hello “+name+”!”

option=raw_input("Please enter C for circle or T for triangle: ")

if option==“C” or “c”:
radius=float(raw_input("Please enter a radius: "))
area=3.14159radius**2
print "The area is %s " % area
elif option==“T” or “t”:
base=float(raw_input("Please enter the base: "))
height=float(raw_input("Please enter the height: "))
area=base
height/2
print “The area is %s” % area


#2

option == "C" is a comparison; "c" is a state, and as a string primitive with length, always evaluates to True, so what your expression above is reading like is,

if condition or True

which will always be True.


#3

So probably that’s why it asks me for a radius when I enter t…


#4

Precisely. Be sure that when comparing two states with OR or with AND, that the conditional is applied to both, as discrete operands.

if a == "A" or a == "a"

#5

One more question. I’m getting an error in the elif line, but I don’t know what could be wrong…

name=raw_input("What's your name? ")

print "Hello "+name+"!"

option=raw_input("Please enter C for circle or T for triangle: ")

if option=="C" or option=="c":
  radius=float(raw_input("Please enter a radius: "))
  area=3.14159*radius**2
  print "The area is %s " % area
  elif option=="T" or option=="t":
    base=float(raw_input("Please enter the base: "))
    height=float(raw_input("Please enter the height: "))
    area=base*height/2
    print "The area is %s" % area

#6

Check your indentation. In Python this is critical in order for the interpreter to identify blocks.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.