简体   繁体   English

我如何构造一个 while 循环以在打印语句中不包含空字符串或退出条目?

[英]How do I structure a while-loop to not include an empty-string or quit entry in a print statement?

In my program, the user is supposed to enter a pizza-topping, then press 'enter', at which time a message is printed that says 'We'll add (topping) to your pizza.'在我的程序中,用户应该输入一个披萨配料,然后按“回车”,此时会打印一条消息,上面写着“我们将添加(配料)到你的披萨中”。

In the case of the user entering an empty string, I want to print the message "Please enter a topping.".在用户输入空字符串的情况下,我想打印消息“请输入浇头。”。

In the case of the user entering 'quit' I want to exit the while-loop.在用户输入“退出”的情况下,我想退出 while 循环。

Currently, if the user enters an empty-string, or 'quit' the program prints the message 'We'll add to your pizza.'目前,如果用户输入空字符串或“退出”,程序将打印消息“我们将添加到您的披萨中”。 Or, We'll add quit to your pizza.', respectively.或者,我们将分别在您的披萨中添加退出。',分别。

prompt = "\nPlease enter the topping you want and press 'enter'"
prompt += "\nType 'quit', then press 'enter' when you're finished:"
active = True
while active:

    topping = raw_input(prompt)
    if topping == '':
        print("Please enter a topping.")

    elif topping == 'quit':
        print("\nThank you.")
        active = False

    else:
        print("\n We'll add {} to your pizza.".format(topping))

I'm sure there is a simple problem with my structure, I just can't seem to find it.我确定我的结构有一个简单的问题,我似乎找不到它。 Any help is appreciated!任何帮助表示赞赏!

Your code works fine, and you're likely running into an issue with trailing characters like @Blupper mentioned.您的代码运行良好,并且您可能会遇到像@Blupper 提到的尾随字符的问题。 If you wanted to implement a simple way of sanitizing your inputs you could refactor topping as:如果你想实现一种简单的方法来清理你的输入,你可以将顶部重构为:

topping = raw_input(prompt).strip()打顶 = raw_input(prompt).strip()

The strip would remove any trailing characters.该条将删除任何尾随字符。

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

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