如果输入在 if 语句中留空则中断
Break if input left blank inside of an if statement
我有一个 Python 的学校作业,其中我有一个物品背包,需要编写代码询问用户是否要:a) 向背包添加物品,b) 检查背包中的物品,c) 退出程序。
对于我的代码,我想这样做,如果用户在输入时添加新项目只是点击 return 并将输入留空,它将再次提示输入而不是如果没有实际添加项目,则继续代码。这是我目前拥有的:
import sys
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if (userChoice == "1"):
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
else:
itemsInBackpack.insert(0, itemAddNew)
print("Added to backpack.")
这里使用我的代码,即使我在测试中点击 return 并将输入留空,代码仍然继续向前并且不会中断以再次提示输入。是因为我已经在 if 语句中使用了 if 语句吗?我确信总的来说有更好的方法来做到这一点,但作为一个初学者我被难住了并且可以在正确的方向上使用推力。
break
停止循环中的所有内容并导致程序结束。
如果你想提示输入直到用户给你一些东西,改变这个:
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
对此:
print("What item do you want to add to the backpack?")
itemAddNew = input()
while itemAddNew == "":
#Added some output text to tell the user what went wrong.
itemAddNew = input("You didn't enter anything. Try again.\n")
这将在文本为空时继续进行。
我有一个 Python 的学校作业,其中我有一个物品背包,需要编写代码询问用户是否要:a) 向背包添加物品,b) 检查背包中的物品,c) 退出程序。
对于我的代码,我想这样做,如果用户在输入时添加新项目只是点击 return 并将输入留空,它将再次提示输入而不是如果没有实际添加项目,则继续代码。这是我目前拥有的:
import sys
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if (userChoice == "1"):
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
else:
itemsInBackpack.insert(0, itemAddNew)
print("Added to backpack.")
这里使用我的代码,即使我在测试中点击 return 并将输入留空,代码仍然继续向前并且不会中断以再次提示输入。是因为我已经在 if 语句中使用了 if 语句吗?我确信总的来说有更好的方法来做到这一点,但作为一个初学者我被难住了并且可以在正确的方向上使用推力。
break
停止循环中的所有内容并导致程序结束。
如果你想提示输入直到用户给你一些东西,改变这个:
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
对此:
print("What item do you want to add to the backpack?")
itemAddNew = input()
while itemAddNew == "":
#Added some output text to tell the user what went wrong.
itemAddNew = input("You didn't enter anything. Try again.\n")
这将在文本为空时继续进行。