【问题标题】:Why is my "If" statement being triggered?为什么我的“If”语句被触发?
【发布时间】:2019-02-08 15:06:58
【问题描述】:

这是我的第一篇文章,如果我做错了什么,我深表歉意。

我目前正在为大学课程编写一个简单的程序。这个特定部分的说明说:

条目的值必须是“1”、“2”或“3”。您可以通过多种方式对此进行测试。

如果您愿意,您可以创建不同的验证技术,只要它们有效。如果输入无效,则以 适当的错误信息并重新提示。

现在,当我提示用户输入选择时(假设他们输入“1”),它认为这是一个无效输入。

我个人认为它应该将答案作为int 值,但说明说不应该。我在这里错过了什么小东西吗?

我尝试使用不同的'" 标记编辑代码。我想我可能会犯一个小的语法错误,但我无法解决它。

cont= str("y")
cart = int(0)
item_total = int(0) 
order_total= float(0)

cont=input("Would you like to place an order? ")
while(cont.lower() == "y"):
  print("Order for John Doe")
  print("1. Savannah")
  print("2. Thin Mints")
  print("3. Tagalongs")
  item_n=input("Please choose a flavor ")
  if(item_n != "1" or item_n != "2" or item_n != "3"):
    print("Invalid entry, please try again")
  else:
    new_item=int(input("How many would you like (1-10)"))

我希望如果您输入 1、2 或 3,它将进入 else 嵌套,但事实并非如此。如果需要,我还可以发布更多教授的说明。

【问题讨论】:

  • I expect that if you enter a 1, 2, or 3 it will go into the else nest 如果输入 1,item_n != "1" or item_n != "2" or item_n != "3" 的计算结果为 False or True or True -> True
  • 更改或到和。
  • 更好的是,使用item_n not in ('1', '2', '3')。不要做item_n not in '123'。这将匹配 1223123
  • 我交换了我的 if 和 else 语句并将“!=”更改为“==”,它似乎工作正常!不过我明白你的意思了,谢谢你的回答。我也不确定如何将此问题标记为已接受。

标签: python string int


【解决方案1】:

你应该使用这个

item_n=int(input("Please choose a flavor "))

而不是这个

item_n=input("Please choose a flavor ")

因为输入函数需要字符串,所以你需要将它转换成 int

在 if 语句中使用 AND 而不是 OR

【讨论】:

    【解决方案2】:

    您应该使用 AND 而不是 OR。因为它不应该是 1 AND not 2 AND not 3 错误。

    【讨论】:

    • 我交换了我的 if 和 else 语句并将“!=”更改为“==”,它似乎工作正常!不过我明白你的意思了,谢谢你的回答。我也不确定如何将此问题标记为已接受。
    【解决方案3】:

    试试这个:

    cont= str("y")
    cart = int(0)
    item_total = int(0)
    order_total= float(0)
    
    cont=input("Would you like to place an order? ")
    while(cont.lower() == "y"):
      print("Order for John Doe")
      print("1. Savannah")
      print("2. Thin Mints")
      print("3. Tagalongs")
      item_n=input("Please choose a flavor ")
    
      if(item_n not in ["1","2","3"]):
        print("Invalid entry, please try again")
      else:
        new_item=int(input("How many would you like (1-10)"))
    

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2012-12-20
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      相关资源
      最近更新 更多