繁体   English   中英

为什么触发“如果”语句?

[英]Why is my “If” statement being triggered?

这是我的第一篇文章,因此对任何不正确的操作表示歉意。

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

条目的值必须为“ 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嵌套,但不会。 如果需要,我还可以发布更多教授的指示。

你应该用这个

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

代替这个

item_n=input("Please choose a flavor ")

由于输入函数需要字符串,因此您需要将其转换为int

并在if语句中使用AND代替OR

您应该使用AND而不是OR。 因为它不应该1 AND不2 AND不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)"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM