简体   繁体   中英

How to ask one question at a time for a math quiz

This is supposed to generate a random math quiz with random numbers and operators. How do I get it to print one question at a time and if they get the answer right add it to their score?

score = 0

for i in range(10):
   ops=['+','-','*','//']
   num1 = random.randint(1,20)
   num2 = random.randint(1,20)
   if ops == '+':
       answer=num1+num2
   elif ops == '-':
       answer = num1-num2
   elif ops == '*':
       answer = num1*num2  
   elif ops == "//":
       answer == num1//num2
   print(num1,ops[random.randint(0,3)],num2,'=')
         

Here is a fixed version of your code. You had several mistakes.

  • you needed to choose an operator (I used here random.choice )

  • answer == num1//num2 needed a simple =

  • you can use input to request user input

import random
n = 10
score = 0
for i in range(n):
   ops=['+','-','*','//']
   num1 = random.randint(1,20)
   num2 = random.randint(1,20)
   op = random.choice(ops)
   if op == '+':
       answer = num1+num2
   elif op == '-':
       answer = num1-num2
   elif op == '*':
       answer = num1*num2
   elif op == "//":
       answer = num1//num2
   try:
       test = int(input(f'{num1} {op} {num2} = '))
   except ValueError:
       print('invalid input')
       continue
   if answer == test:
       print('correct!')
       score += 1
   else:
       print(f'wrong, the answer was: {answer}')
print(f'you scored {score}/{n}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM