【问题标题】:Python if does not behave as expectedPython if 的行为不符合预期
【发布时间】:2015-07-04 16:39:38
【问题描述】:

我正在尝试制作一个 python 计算器。但由于某种原因,它只会输出平方根选项。
我目前在 iPhone 上使用 python3.4 和 3.3 模拟器,但在这两种设备上都有同样的问题。

print("This program is a calculator app \n Creator: AtPython")
print("...")
Print("please choose a       mathematical operation")
Opt = input("square-root. \n addition, \n subtraction, \n multiplication, \n division: ")

if opt == "square-root" or "squareroot":
    num = float(input('Enter a number: '))
    num_sqrt = num ** 0.5
    print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
    input("Press 'Enter' to exit")

If opt == "addition":
    add_1 = float(input("Please enter a number"))
    add_2 = float(input("Please enter another number")) 
    add_ans = add_1 + add_2
    print(add_ans)
    qus = input("Would you like to add   another number? [y/n]")
    
elif qus == "y":
    add_3 = float(input("Enter a third number"))
    input("Press 'Enter' to exit")
    
else:
    input("Press 'Enter' to exit")

【问题讨论】:

  • 您发布的代码中有许多语法错误。不确定这些是否存在于原始文件中,或者它们是否在 SO 上格式错误。
  • @Ming 只更改了缩进和一些标点符号。
  • 你能修复你的空白吗?

标签: python


【解决方案1】:
if opt == "square-root" or "squareroot":

这不会解析为if opt == "square-root" or opt == "squareroot": 这会解析为if (opt == "square-root") or bool("squareroot"),它会返回True,因为在字符串上调用bool 始终是True,除非字符串为空。 (更多信息请参见link)

解决办法是:

if opt == "square-root" or opt == "squareroot":

或

if opt in ["square-root","squareroot"]:

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2022-01-06
    相关资源
    最近更新 更多