【问题标题】:Python Sentinel ValuePython 哨兵值
【发布时间】:2017-04-20 17:24:00
【问题描述】:

我是一名乞讨的 Python 学生,正在创建一个数学测验程序。测验本身有效,但我遇到的问题是继续测验,直到用户希望通过输入哨兵值退出。我曾尝试在几个地方使用哨兵值,但要么程序完全停止,要么程序陷入无限循环。只需要关于在哪里正确放置哨兵值的建议。

 import random 

 a = random.randint(1,15)
 b = random.rantint(1,15)

 c = a + b

  while flag != -1
     print("Enter the sum of", a, "+",b)

      d=int(input())
      if (c==d):
         print("Correct")
      else:
         print("Incorrect, the correct answer is", c)

      flag = int(input("If you would like to continue enter 1 or -1 to quit))

      if (flag < 0) :
         print ("Quiz complete")

【问题讨论】:

  • 你应该看看“break”关键字,它可以让你退出循环。

标签: python sentinel


【解决方案1】:

看看以下是否有效

import random 

flag = 0
while flag != -1:
    a = random.randint(1,15)
    b = random.randint(1,15)
    c = a + b
    print("Enter the sum of", a, "+",b)
    d=int(input())
    if (c==d):
        print("Correct")
    else:
        print("Incorrect, the correct answer is", c)

    flag = int(input("If you would like to continue enter 1 or -1 to quit: "))

    if (flag < 0) :
        print ("Quiz complete")

【讨论】:

    【解决方案2】:

    如前所述,在这里休息一下会有所帮助,

    While True:
        flag = int(input())
        if(flag < 1):
           # This will break the While Loop, thus exiting the program
           break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 2022-01-23
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多