您将如何编程一个循环一个问题的循环直到回答正确?我如何编码一条消息以表明他们回答错了

布兰登·亨特

我刚刚在一个月前开始学习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解决了我的问题,却找不到能完全解决我的问题的东西。
百里香
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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章