在python中使用while检查时出错

2024-06-01 22:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

while True:
    self.soil_type = input("Please choose soil type - alkaline, neutral, acidic: ")
    print('-'*30)
    print('')
    if self.soil_type != "alkaline" and "neutral" and "acidic":
        print("***NOT A VALID SOIL TYPE***")
        continue
    else:
        False

我想用while循环进行错误检查。 如果我键入的不是碱性、中性、酸性,请打印“不是有效的土壤类型”,然后继续输入命令。如果我键入了一种正确的土壤类型,请退出循环并转到下一步。你知道吗

但没用。即使我输入了正确的一个(例如“酸性”),它显示“不是一个有效的土壤类型”。我错过了什么?:)


Tags: andselftrue类型input键入typeprint
3条回答

您使用的if条件是错误的。你知道吗

应该是这样的-

while True:
    self.soil_type = input("Please choose soil type - alkaline, neutral, acidic: ")
    print('-'*30)
    print('')
    if (self.soil_type != "alkaline") and (self.soil_type != "neutral") and (self.soil_type != "acidic"):
        print("***NOT A VALID SOIL TYPE***")
        continue
    else:
        False

原因是你把它说成-

if <condition> and "neutral" and "acidic":
     ...

因为“中性”和“酸性”只是真值,如果不是碱性,第一个条件就是真的。这使得整个情况属实,它只是打印-

***NOT A VALID SOIL TYPE***

希望这有帮助。你知道吗

如果您选择if something,那么您的代码将更可读,而不是选择if not something

while True:
    self.soil_type = input("Please choose soil type - alkaline, neutral, acidic: ")
    print('-'*30)
    print('')
    if self.soil_type == "alkaline" or self.soil_type == "neutral" or self.soil_type == "acidic":
      print("**VALID**")
      print self.soil_type
      break
    else:
      print("***NOT A VALID SOIL TYPE***")

提醒(布尔代数):

The rules can be expressed in English as:

  • the negation of a disjunction is the conjunction of the negations; and
  • the negation of a conjunction is the disjunction of the negations; or

  • the complement of the union of two sets is the same as the intersection of their complements; and

  • the complement of the intersection of two sets is the same as the union of their complements.

or

not (A or B) = not A and not B; 
and
not (A and B) = not A or not B

https://en.wikipedia.org/wiki/De_Morgan%27s_laws

while True:
    self.soil_type = input("Please choose soil type - alkaline, neutral, acidic: ")
    print('-'*30)
    print('')
    if not(self.soil_type == "alkaline" or self.soil_type == "neutral" or self.soil_type == "acidic"):
        print("***NOT A VALID SOIL TYPE***")
        continue
    else:
        break

试着用这个……应该有用!你知道吗

相关问题 更多 >