繁体   English   中英

在Python 3中生成随机数学

[英]Generate Random Math in Python 3

该程序将询问用户有关两个数字的一​​系列问题。 这两个数字将在1到10之间随机生成,并会询问用户10次。 在这10个问题的末尾,程序将显示从这些问题中有多少用户正确了。 每个问题都应在决定乘积,总和或差额之间随机决定。 将询问的问题以及验证用户输入分开。

我尝试使用三个乘积,总和或差随机生成。 我尝试使用z = random.randint(1, 4)是从1是乘积,2是和或3是差中选择,然后与变量z为1时进行乘积运算,或者如果var z为3,那么应该像x / y那样有所不同,但是我无法确定它是否完成了它。 初次使用产品时,我有预期的结果,但是它可以工作,所以我只需要加上总和和差额即可。

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

> 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表示和,而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格式,所有内容都是敏感的,仍然与运行输出相同。 任何帮助将通过解释得到更多的赞赏。 (我希望自从我聋了以后我的英语就可以理解)我从星期六开始,比预期的准时开会。

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


如果您使用'+','-','*','/'而不是1,2,3,4来映射您的操作,则可以ops = random.choice("+-*/")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.
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循环放在同一垂直线上。

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

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

用作参考以获取有关随机的更多信息

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)

将其与运营商列表进行比较。


示例:operator = 2

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

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

输出:

What is 3  / 2?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM