首页 > 解决方案 > 在 Python 3 中生成随机数学

问题描述

该程序将向用户询问有关两个数字的一​​系列问题。这两个数字将在 1 到 10 之间随机生成,并且会询问用户 10 次。在这 10 个问题结束时,程序将显示用户从这些问题中答对了多少。每个问题应随机决定询问乘积、总和或差。将询问的问题与验证用户输入分开。

我尝试使用三个乘积、总和或随机差来生成。我尝试使用z = random.randint(1, 4)的是从 1 是产品,2 是总和,或 3 是差值中选择,然后我使用 if variablez是 1,然后做产品数学或如果 varz是 3,那么它应该是这样的差异x / y,但我想不通它完成它。当我第一次使用 product 运行时,我得到了预期的结果,但它可以工作,所以我只需要添加包含总和和差异。

产品的预期输出有些对于分数测试不正确):

> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10

我只为产品工作(成功):

import random

def askNum():
  while(1):
    try:
      userInput = int(input("Enter a number: "))
      break
    except ValueError:
      print("Incorrect Input!")

  return userInput

def askQuestion():

  x = random.randint(1, 100)
  y = random.randint(1, 100)

  print("What is " + str(x) + " x " +str(y))

  u = askNum()

  if (u == x * y):
    return 1
  else:
    return 0

amount = 10
correct = 0
for i in range(amount):
  correct += askQuestion()

print("You got %d correct out of %d" % (correct, amount))

我目前的工作:(我正在努力像预期的输出一样添加总和和差异

更新:在预期的输出与产品很好地配合之后,我尝试为z1-3 添加新的随机整数,这意味着我使用 1 表示产品,2 表示总和,3 是通过使用给定的 if 语句的差异随机选择。我在这方面很挣扎,这是我停下来想办法随机做数学的地方,因为我现在是 Python 的新手一个多月了。

import random

def askNum():
  while(1):
    try:
      userInput = int(input("Enter a number: "))
      break
    except ValueError:
      print("Incorrect Input!")

  return userInput

def askQuestion():

  x = random.randint(1, 10)
  y = random.randint(1, 10)
  z = random.randint(1, 4)

  print("What is " + str(x) + "  "+ str(z)+ " " +str(y))

  u = askNum()

    if (z == 1):
      x * y  #product
      return 1
    else if (z == 2):
      x + y #sum
      return 1
    else if (z == 3):
      x / y #difference
      return 1
    else
      return 0

amount = 10
correct = 0
for i in range(amount):
  correct += askQuestion()

print("You got %d correct out of %d" % (correct, amount))

输出

md35@isu:/u1/work/python/mathquiz> python3 mathquiz.py
  File "mathquiz.py", line 27
    if (z == 1):
    ^
IndentationError: unexpected indent
md35@isu:/u1/work/python/mathquiz>

有了这个当前的输出,我再次检查了更正的 Python 格式,一切都很敏感,并且仍然与运行输出相同。任何帮助都会得到解释。(我希望我的英语可以听得懂,因为我是聋子)我从星期六开始这个,比预期的准时见面。

标签: pythonpython-3.xmathrandomsymbolic-math

解决方案


您的问题是 python 3 不允许混合空格和制表符进行缩进。使用显示使用的空格(并手动修复)的编辑器或将制表符替换为空格的编辑器。建议使用 4 个空格进行缩进 - 阅读PEP-0008了解更多样式提示。


如果您使用'+','-','*','/'而不是1,2,3,4映射您的操作,您可以使您的程序不那么神秘:ops = random.choice("+-*/")将您的运算符之一作为字符串。您将它输入一个calc(a,ops,b)函数并从中返回正确的结果。

您还可以缩短askNum并提供要打印的文本。

这些可能看起来像这样:

def askNum(text):
    """Retunrs an integer from input using 'text'. Loops until valid input given."""
    while True:
        try:
            return int(input(text))
        except ValueError:
            print("Incorrect Input!")

def calc(a,ops,b):
    """Returns integer operation result from using : 'a','ops','b'"""
    if   ops == "+": return a+b
    elif ops == "-": return a-b
    elif ops == "*": return a*b
    elif ops == "/": return a//b   # integer division
    else: raise ValueError("Unsupported math operation")

最后但并非最不重要的一点是,您需要修复除法部分 - 您只允许整数输入,因此您也只能给出可以使用整数答案解决的除法问题。

程序:

import random

total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
    ops = random.choice("+-*/")
    a,b = random.choices(nums,k=2)

    # you only allow integer input - your division therefore is
    # limited to results that are integers - make sure that this
    # is the case here by rerolling a,b until they match
    while ops == "/" and (a%b != 0 or a<=b):
        a,b = random.choices(nums,k=2)

    # make sure not to go below 0 for -
    while ops == "-" and a<b:
        a,b = random.choices(nums,k=2)

    # as a formatted text 
    result = askNum("What is {} {} {} = ".format(a,ops,b))

    # calculate correct result
    corr = calc(a,ops,b)
    if  result == corr:
        correct += 1
        print("Correct")
    else:
        print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))

print("You have {} out of {} correct.".format(correct,total))

输出:

What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.

推荐阅读