在Python 3中生成随机数学

问题描述 投票:0回答: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))

我目前的工作:(我正在努力增加和预期输出之和

更新:预期输出与产品配合良好后,我试图为z添加新的随机int 1-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))

OUTPUT:

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 python-3.x math random symbolic-math
3个回答
2
投票

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

0
投票
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循环应该在同一条垂直线上。


0
投票

要生成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)

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


示例:operator = 2

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

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

输出:

What is 3  / 2?
© www.soinside.com 2019 - 2024. All rights reserved.