python - 圆计算器无法正常工作

标签 python if-statement

代码是用python 3.3编写的,仅适用于第一个if语句,即使if语句错误,也不会确认其他elif语句。

calccircle()

你知道哪些数据?半径

Enter Diameter def calccircle():
      x = input("What data do you know? ")
      if x == "Diameter" or "diameter":
          a = int(input("Enter Diameter "))
          print("Circumference is", a * math.pi)
          print("Area is", math.pi * math.pow(a/2,2))
          print("Radius is:",a/2)
      elif x == "Radius" or "radius":
          b = input("Enter radius: ")
          print("Circumference is", b * 2 * math.pi)
          print("Area is", math.pi * math.pow(b,2))
          print("Diameter is", b * 2)
      elif x == "area" or "Area":
          c = input("Enter area: ")
          print("Circumference is", ((math.sqrt(c))/math.pi) * b * 2 * math.pi)
          print("Diameter is", math.sqrt(c) * math.pi * 2)
          print("Radius is", math.sqrt(c) * math.pi)
      elif x == "circumference" or "Circumference":
          d = input("Enter Circumference: ")
          print("Area is", math.pi * math.pow(d/math.pi,2))
          print("Diameter is", d/math.pi * 2)
          print("Radius is", d/math.pi)

它显示输入(“输入直径:”)并且不注意我写的内容或 if 语句。

calccircle() What data do you know? radius Enter Diameter

请注意,我写了 radius,并且 input("Enter radius: ") 应该运行,但它没有运行。请帮忙。

最佳答案

您的问题是这样的:

 if x == "Diameter" or "diameter":

看起来像Python:

 if (x == "Diameter") or "diameter":

其中,当 x != "Diameter" ,就像:

if "diameter":

总会经历的。

Python 对待 False, None, "", [], {}, ...以及类似的 Falseif的背景下语句(或者如果您在它们上或其他各个地方调用 bool ),以及大多数其他内容作为 True 。这通常很方便,但可能会导致对 or 的轻微混淆。声明让很多不习惯Python的人犯这个错误。

相反,请执行以下操作之一:

if x == "Diameter" or x == "diameter":  # most direct translation
if x in {"Diameter", "diameter"}:  # very slightly faster, a little less typing
if x.lower() == "diameter":  # also allows DIAmeter, etc

还值得注意的是,如果您写了类似的内容

if x == ("Diameter" or "diameter"):

这与

相同
if x == "Diameter":

"Diameter" or "diameter"看到"Diameter"True ish,因此返回该值。

关于python - 圆计算器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867103/

相关文章:

swift - 有没有办法根据之前是否在另一个 View Controller 上按下按钮来编写 if 语句?

python - 在 rpy2 中处理 Null 返回

python - Tesseract 无法读取这串极其简单的数字

python - 关于QML和PySide2的几个问题

python - 将数据库数据从 DEV 移动到 PRODUCTION,最佳实践?

python - 只能将元组(不是 "unicode")连接到元组

python - 重构重复的 if 语句

javascript - 打印出数组中随机生成的数字后,在 2 个偶数之间添加破折号

c# - 如何从 robots.txt 文件中读取站点地图 url 文本

linux - 在 Shell 脚本中传递 'If statement' 问题