if-else语句未运行elif-或else-子句

时间:2018-10-14 00:43:48

标签: python if-statement

我正在使用Python尝试创建一个面积计算器(类似于Code Academy的计算器)。只有我的else语句似乎正在运行:

clientslist.txt

我使用PyCharm编辑文本,没有语法错误或任何其他类型的错误返回。无论我对答案输入做出什么回应(无论它们是整数还是语法),代码始终显示print("Area Calculator.") print ("Select Shape:") print ("Circle or Triangle? ") answer = input() if answer == "Circle" or "C" or "c" or "circle": radius = float(input("Input Radius: ")) area_c = (3.12159 * radius) * 2 print (area_c) elif answer == "Triangle" or "T" or "t" or "triangle": base = float(input("Input Base: ")) height = float(input("Input Height: ")) area_t = (.5 * base) * height print (area_t) else: print ("error")

对不起,事实证明这很容易解决。我刚开始使用Python,并尝试了各种缩进和语法变化,但无济于事。

3 个答案:

答案 0 :(得分:0)

使用:

print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")

answer = input()

if answer.lower() in {"circle","c"}:
    radius = float(input("Input Radius: "))
    area_c = (3.12159 * radius) * 2
    print (area_c)

elif answer.lower() in {"triangle","t"}:
    base = float(input("Input Base: "))
    height = float(input("Input Height: "))
    area_t = (.5 * base) * height
    print (area_t)

else:
    print ("error")

更改是带有or的行,请改用in,以便按集合进行检查

那是不同的。

请注意使用lower来简化长度

请注意使用set来提高速度(更快)

答案 1 :(得分:-1)

您错误地使用了==运算符。您必须以这种方式使用它:

if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":

更简单的方法是使用检查您的字符串是否匹配元组或列表中的任何项目。因此,您的代码将需要像这样修改:

print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")

answer = input()

if answer in ("Circle", "C", "c", "circle"):
    radius = float(input("Input Radius: "))
    area_c = (3.12159 * radius) * 2
    print (area_c)

elif answer in ("Triangle", "T", "t", "triangle"):
    base = float(input("Input Base: "))
    height = float(input("Input Height: "))
    area_t = (.5 * base) * height
    print (area_t)

else:
    print ("error")

答案 2 :(得分:-2)

Struct1 mystruct;
相关问题