Python,数学测验。被问到的问题并没有接受答案

时间:2018-03-25 16:18:39

标签: python python-3.x math random

我试图写一个小的python程序,询问随机数学问题,但我被卡住了。即使答案是正确的,被询问的随机问题也不接受答案。此外,它不断重复这个问题。能否请您查看我的代码,让我知道我错过了什么?

import random
import operator
import time

name = input("Type your name: ") #user name is stored inside name variable
print ("Hi",name,"This math quiz will test your basic math ability.") #Quick 
intro
print ("Please press 'Enter' after every input")
print (" ")

time.sleep(1)

operators = {
           '+': operator.add,
           '-': operator.sub,
           '*': operator.mul,
           '/': operator.truediv
           }

randNum1 = random.randint(9, 999)
randNum2 = random.randint(9, 999)

ops = random.choice(list(operators.keys()))

question = 0
star = 0

def ask_Question():

    que = randNum1, ops, randNum2
    print ("What is", randNum1, ops, randNum2)
    que_ans = int(input(">>>"))

    if que == que_ans:
        print ("Congrats! You earned your first star.")
        print (" ")

    elif que != que_ans:
        print ("Error! Better luck next time.")

def main():

    while question <= 4:
        ask_Question()

main()

1 个答案:

答案 0 :(得分:0)

在问题中生成随机数,并计算操作结果:

import random
import operator
import time

name = input("Type your name: ") #user name is stored inside name variable
print ("Hi",name,"This math quiz will test your basic math ability.") #Quick intro
print ("Please press 'Enter' after every input")
print (" ")

time.sleep(1)

operators = {
           '+': operator.add,
           '-': operator.sub,
           '*': operator.mul,
           '/': operator.truediv
           }

randNum1 = random.randint(9, 999)
randNum2 = random.randint(9, 999)

ops = random.choice(list(operators.keys()))

question = 0
star = 0

def ask_Question():

    # You must generate new random numbers and operation in *each* question
    randNum1 = random.randint(9, 999)
    randNum2 = random.randint(9, 999)
    ops = random.choice(list(operators.keys()))

    # operators[ops] is your mathematical function, you must call it 
    # with your numbers as parameters
    que = operators[ops](randNum1, randNum2)

    print ("What is", randNum1, ops, randNum2)
    que_ans = int(input(">>>"))

    if que == que_ans:
        print ("Congrats! You earned your first star.")
        print (" ")

    elif que != que_ans:
        print ("Error! Better luck next time.")

def main():

    while question <= 4:
        ask_Question()

main()