如果在if语句内输入为空则中断

问题描述 投票:0回答:1

我有一个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.")

使用我的代码,即使我在测试中按回车键并将输入保留为空白,代码仍继续向前,并且不会中断以再次提示输入。是因为我已经在if语句中使用了if语句吗?我敢肯定,总的来说,有一种更好的方法可以做到这一点,但是作为一个初学者,我很沮丧,可以在正确的方向使用推子。

python if-statement input break
1个回答
0
投票

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")

这将继续进行,直到文本为空。

© www.soinside.com 2019 - 2024. All rights reserved.