while循环中的三个If语句

时间:2016-03-23 10:37:58

标签: python loops if-statement while-loop

我的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) 

2 个答案:

答案 0 :(得分:0)

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) 

可以做得更好,映射运算符等等。我允许你这样做:)

答案 1 :(得分:0)

循环运行少于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所述的整个代码!