【问题标题】:How would you program a loop that loops a certain question until answered right? How can I code a message to show that they answered it wrong [duplicate]你将如何编写一个循环来循环某个问题直到回答正确?我如何编码一条消息以表明他们回答错误[重复]
【发布时间】:2020-12-02 20:10:18
【问题描述】:

我一个月前刚开始学习 python,我一直想创建一个选择你的故事提示。

看起来像这样

while True:
    try:
        party = int(input("How many people joined the party "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue

我注意到但不知道如何解决的一些事情是这样的

  1. 我无法设置加入派对的最大人数,如果没有,无论如何它都会不断循环输入消息。
  2. 我无法停止负输入
  3. 我无法输入“请在下面输入一个数字” 抱歉,如果这很愚蠢,我刚来到一个通常在 python 中解决我的问题的网站,却找不到完全解决我的问题的东西。

【问题讨论】:

    标签: python python-3.x loops


    【解决方案1】:
    while True:
        try:
            party = int(input("How many people joined the party (1-5)?:"))
        except ValueError:
            print("\nSorry, I didn't understand that.")
            continue
    
        if 0 < party <= 5:
            print(f"{party} people joined") 
            break
    
        print(f"\nInvalid answer, please insert a number between 1 and 5")
    

    说明

    数字验证是​​您必须在int(input(...)) 之外执行的操作。就我而言,我验证最终答案是否在 0 到 5 之间。如果是,我将打破 while 循环。如果答案不在该范围内,我会打印一条消息,提示他们必须在正确的范围内插入一个值。

    示例

    How many people joined the party (1-5)?: 0
    
    Invalid answer, please insert a number between 1 and 5
    How many people joined the party (1-5)?: I and my best friend
    
    Sorry, I didn't understand that.
    How many people joined the party (1-5)?: 3
    3 people joined
    

    【讨论】:

    • 它在“print(f"{party} 人加入")”上给了我一个错误
    • 您提供了哪些错误,以及提供了什么输入?
    • f-strings 是从 python 3.6+ 开始的,所以如果你有较低的版本,你必须使用:print("{:d} people joined".format(party))。我更新了我的答案以兼容 python 3.6
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 2020-08-13
    • 2019-06-21
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多