while循环中的三个If语句

2024-06-16 11:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: answeriftimeissleepthisscoreexpected
2条回答
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) 

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

循环运行不到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) 

但是考虑重写安东·埃皮钦所说的整个代码!你知道吗

相关问题 更多 >