【问题标题】:Random Arithmetic Quiz Problems随机算术测验问题
【发布时间】:2015-01-15 19:07:58
【问题描述】:

我在一个简单的 python 测验中遇到了问题,它随机生成答案和运算符不胜感激。

这是代码(取自How can I randomly choose a maths operator and ask recurring maths questions with it?):

import random
import time

def randomCalc():
    ops = {'+':operator.add,
           '-':operator.sub,
           '*':operator.mul,
           '/':operator.truediv}
    num1 = random.randint(0,12)
    num2 = random.randint(1,10)    
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?\n'.format(num1, op, num2))
    return answer

def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def quiz():
    print('Welcome. This is a 10 question math quiz\n')
    score = 0
    for i in range(10):
        correct = askQuestion()
        if correct:
            score += 1
            print('Correct!\n')
        else:
            print('Incorrect!\n')
    return 'Your score was {}/10'.format()

【问题讨论】:

  • @Cyber​​ 你为什么不在答案中调用该函数。 OP对你很反感;)
  • @BhargavRao 对不起!我现在正开车到他们的电脑前为他们打字!
  • @Cyber​​:哇,这就解释了! (我不禁想知道 OP 是如何编写如此高质量的代码却不知道如何调用它的。)
  • @Cyber​​ 这是最好的解决方案。最好快点做。还要问OP,operator是怎么变成time

标签: python random


【解决方案1】:

您需要在代码的顶层调用quiz() 函数:

quiz()

你也错过了:

import operator

【讨论】:

    【解决方案2】:

    通过在末尾添加调用语句来调用您的函数。quiz()

    Python 不像 C 或任何其他自动调用 main 方法的语言

    正如 NPE 所发现的,您已将 import operator 更改为 import time。改回来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2019-11-07
      • 2010-10-15
      • 2014-11-15
      • 1970-01-01
      相关资源
      最近更新 更多