python - 我的代码跳过 IF block 并转到 ELSE

标签 python

几个小时前刚开始使用 python,偶然发现了一个问题。 下面的代码片段显示,最初我将 userInput 存储为 1 或 2,然后执行 if block 。问题是代码直接跳转到 else (即使我在控制台窗口中输入 1)。 我知道我犯了一个简单的错误,但我们将不胜感激任何帮助。

使用 Python 3.5 === 在 Visual Studio 2015 中运行 === 特别是 cPython

userInput = float(input("Choose 1 (calculator) or 2 (area check)\n"))
if(userInput =='1') :
    shape = input("Please enter name of shape you would like to calculate the area for\n")

if(shape == 'triangle') :
    base = int(input("Please enter length of BASE\n"))
    height = int(input("Please enter HEIGHT\n"))
    print("The area of the triangle is %f" % ((base * height)*0.5))

elif (shape == 'circle') :
    radius = int(input("Please enter RADIUS\n"))
    print("The Area of the circle is %f" % ((radius**2)*22/7))

elif (shape == 'square') :
    length = int(input("Please Enter LENGTH\n"))
    print("The area of the square is %f" % ((length**2)*4))

else :
    initial1 = float(input("Please enter a number\n"))
    sign1 = input("please enter either +,-,*,/ \nwhen you wish to exit please type exit\n")
    initial2 = float(input("Please enter number 2\n"))
if(sign1 == '+') :
    answer = float(initial1) + float(initial2)
    print(answer)
elif(sign1 == '*') :
    answer = float(initial1) * float(initial2)
    print(answer)
elif(sign1 == '-') :
    answer = float(initial1) - float(initial2)
    print(answer)
elif(sign1 == '/') :
    answer = float(initial1) / float(initial2)
    print(answer)
PS。如果[可能]你能让帮助尽可能简单,因为我想确保我完全理解基础知识。

感谢大家的帮助!! :D

最佳答案

您正在将输入转换为 float ,但检查数字的字符串。将其更改为:

If userInput == 1.0:

或者更好的是,保持原样,只是不要首先将用户输入转换为 float 。如果您想对其进行数学运算,只需将输入转换为 floatint 即可。在您的情况下,您只是将其用作选项,因此您可以将其保留为字符串:

userInput = input("Choose 1 (calculator) or 2 (area check)\n")

附注确保在 Python 中非常小心缩进。我假设您的代码编辑器中的缩进是正确的,但在粘贴到此网站时也要小心。这里的所有内容都处于同一级别,但某些 if block 需要进一步缩进才能使程序正常工作。

关于python - 我的代码跳过 IF block 并转到 ELSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548134/

相关文章:

python - python 中的无限 while 循环

python - 在 Dicts 中查找具有相同值的所有关键元素

python - 如何创建一个负向后查找表达式 - 添加 - 不能是空词

python - 将 JS 变量发布到 Django View 并在单独的模板中显示为上下文变量

python - Pylint 在 vscode 中找不到错误

Python 获取 YQL 结果到 MySQL

python - 如何在scrapy(Python)中间件中实现并发

python - QTextBrowser 无法正确显示反斜杠字符

python - Python 3 中对象和类的关系

python - 如何测试列表中多个值的成员资格?