【问题标题】:Generate Random Math in Python 3在 Python 3 中生成随机数学
【发布时间】:2019-03-05 05:59:25
【问题描述】:

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

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

EXPECTED OUTPUT 与产品(一些分数测试不正确):

> 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))

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

更新:在预期输出与产品配合良好之后,我尝试使用 1-3 为 z 添加新的随机整数,这意味着我使用 1 表示产品,2 表示对于 sum 和 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 格式,所有内容都是敏感的,并且仍然与运行输出相同。任何帮助都会得到解释。 (我希望我的英语可以听得懂,因为我是聋子)我从星期六开始这个,比预期的准时见面。

【问题讨论】:

  • 尝试将else if 替换为elif。现在可以用了吗?
  • 在 u=askNum() 之后你的 if 块缩进了错误
  • 好的@Lomtrur,我已将所有else if 替换为elif,但它仍然是相同的输出,没有任何改变?
  • @mamun,我很困惑,但 u=askNum() 是用户输入的答案...

标签: python python-3.x math random symbolic-math


【解决方案1】:

您的问题是 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.

【讨论】:

    【解决方案2】:
    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
      elif (z == 2):
        x + y #sum
        return 1
      elif (z == 3):
        x / y #difference
        return 1
      else:
        return 0
    

    像这样写你的块,你的 u = askNum() 和下一个 if 循环应该在同一条垂直线上。

    【讨论】:

    • else if 是无效的语法。 else 后面没有冒号(倒数第二行)。
    • 是的,我更关注给定的问题,即 IndentationError。谢谢指正。
    【解决方案3】:

    要生成 n 个随机数,您可以使用

    random.sample(range(from, to),how_many_numbers)
    

    用户 this 作为参考了解更多关于随机的信息

    import random
    
    low=0
    high=4
    n=2 #no of random numbers
    
    
    rand = random.sample(range(low, high), n)
    
    #List of Operators
    arithmetic_operators = ["+", "-", "/", "*"];
    operator = random.randint(0, 3)
    
    x = rand[0];
    y = rand[1];
    result=0;
    # print(x, operator, y)
    
    if (operator == 0):
        result = x + y# sum
    
    elif(operator == 1):
        result = x - y# difference
    
    elif(operator == 2):
       result= x / y#division
    
    else :
        result=x * y# product
    
    
    print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))
    

    下面存储一个随机数(int)

    operator = random.randint(0, 3)
    

    将其与运算符列表进行比较。


    示例:运算符 = 2

    elif(operator == 2):
       result= x / y#division
    

    此代码将被执行,并且由于 operator=2,将选择 list(/) 中的第三个元素

    输出:

    What is 3  / 2?
    

    【讨论】:

    • 抱歉解释不好
    猜你喜欢
    • 1970-01-01
    • 2017-12-31
    • 2015-12-20
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多