Python数学测验随机数

时间:2015-03-06 15:29:19

标签: python loops math random

你好我正在尝试为随机数学测验生成器制作代码我有它所以它randoms数字和操作,但我不能让它重复10次,因为我想要它问10个问题可以有人帮助请在这里是我的代码

import random
import time

name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
finish= False
ops = ['+', '-', '*']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation = random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Your first question is",rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
    print ("Correct")
    score=score+1
else:
    print ("Incorrect. The actual answer is",maths)

2 个答案:

答案 0 :(得分:1)

在条件下使用 while 循环。

ALGO:

  1. counter设为0
  2. 使用while循环并检查counter是否少于10
  3. 向用户提问。
  4. 做你的计算。
  5. counter增加一个。
  6. counter等于10时,该时间condition将为False
  7. 演示:

    >>> counter = 0
    >>> while counter<10:
    ...    que = raw_input("Enter que:")
    ...    print que
    ...    counter += 1
    ... 
    Enter que:1
    1
    Enter que:2
    2
    Enter que:3
    3
    Enter que:4
    4
    Enter que:5
    5
    Enter que:6
    6
    Enter que:7
    7
    Enter que:8
    8
    Enter que:9
    9
    Enter que:10
    10
    >>> 
    

答案 1 :(得分:0)

使用for循环:

for num in range(5): 
    # Replace "print" below, with the code you want to repeat.
    print(num)

要重复所有问题,不包括"whats your name..",请在循环中包含您需要的部分代码:

import random

name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0

for question_num in range(1, 11):
    ops = ['+', '-', '*']
    rand=random.randint(1,10)
    rand2=random.randint(1,10)
    operation = random.choice(ops)
    maths = eval(str(rand) + operation + str(rand2))
    print('\nQuestion number: {}'.format(question_num))
    print ("The question is",rand,operation,rand2)

    d=int(input ("What is your answer:"))
    if d==maths:
        print ("Correct")
        score=score+1
    else:
        print ("Incorrect. The actual answer is",maths)