【问题标题】:Three If statements in while loopswhile 循环中的三个 If 语句
【发布时间】:2016-07-10 14:31:15
【问题描述】:

我的 while 循环中有三个 if 语句,它们应该在问题变量等于 10 之前提出问题。

但是我认为因为我有三个 if 语句,所以它只问三个问题。我尝试使用 break - 它结束了我的 while 循环

这是我的代码:

while question<10: 
user_answer=input(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers1))) 

if operators == '+': 
    expected_answer = numbers + numbers1 
    if user_answer==expected_answer:
        print ('This is correct!') 
        print ("Your score so far is",score,"out of 10") 
        question=question+1 
        time.sleep(2) 
        print ('This is incorrect!') 
        question=question+1 
        time.sleep(2) 

if operators == '-': 
    expected_answer = numbers - numbers1 
    if user_answer==expected_answer: 
        print ('This is correct!') 
        print ("Your score so far is",score,"out of 10") 
        question=question+1 
        time.sleep(2) 
        print ('This is incorrect!') 
        question=question+1 
        time.sleep(2) 

if operators == '*': 
    expected_answer = numbers * numbers1
    if user_answer==expected_answer: 
        print ('This is correct!') 
        score=score+1 
        print ("Your score so far is",score,"out of 10") 
        question=question+1 
        time.sleep(2) 
        print ('This is incorrect!')  
        question=question+1 
        time.sleep(2) 

【问题讨论】:

  • 请正确缩进您的代码。 Python 使用空格,而其他语言使用大括号。事实上,不可能确定代码块在代码中的位置。事实上,这甚至不应该运行,因为 while 循环不包含任何主体。
  • 你为什么经常重复自己?
  • 那么问题是什么?
  • 是否曾经operators(这是某种集合,因为您使用的是random.choice(operators))等于SINGLE 值? (您的 operators == '*' 测试检查的内容)

标签: python loops if-statement while-loop


【解决方案1】:
while question<10: 
   user_answer=input(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers1))) 

   if operators == '+': 
       expected_answer = numbers + numbers1

   if operators == '-': 
      expected_answer = numbers - numbers1

   if operators == '*': 
      expected_answer = numbers * numbers1

   if user_answer==expected_answer:
       score=score+1
       print ('This is correct!')
   else: 
       print ('This is incorrect!')

   print ("Your score so far is",score,"out of 10")
   question=question+1 
   time.sleep(2) 

可以做得更好,映射运算符等等。我会让你做的:)

【讨论】:

    【解决方案2】:

    循环运行不到 10 次,因为如果答案正确,问题变量会增加两倍。并打印两条消息(“正确”/“不正确”)。你的代码需要'else':

    if user_answer==expected_answer:
        print ('This is correct!') 
        print ("Your score so far is",score,"out of 10") 
        question=question+1 
        time.sleep(2) 
    else:
        print ('This is incorrect!') 
        question=question+1 
        time.sleep(2) 
    

    但请考虑按照 Anton Epikhin 的说法重写整个代码!

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2014-01-21
      • 2015-11-08
      • 2016-01-12
      • 2013-11-01
      相关资源
      最近更新 更多