简体   繁体   English

在Python 3中生成随机数学

[英]Generate Random Math in Python 3

This program will ask the user a series of questions about two numbers. 该程序将询问用户有关两个数字的一​​系列问题。 These two numbers will be generated randomly between 1 and 10 and it will ask the user 10 times. 这两个数字将在1到10之间随机生成,并会询问用户10次。 At the end of these 10 questions the program will display how many the user got correct out of those questions. 在这10个问题的末尾,程序将显示从这些问题中有多少用户正确了。 Each question should randomly decide between asking for the product, sum, or difference. 每个问题都应在决定乘积,总和或差额之间随机决定。 Separate the question asking into a function, as well as the validating user input. 将询问的问题以及验证用户输入分开。

I tried using with three product, sum or difference in random to generate. 我尝试使用三个乘积,总和或差随机生成。 I tried to use z = random.randint(1, 4) is to select from 1 is product, 2 is sum, or 3 is difference and then I used with if variable z is 1, then do product math or if var z is 3, then it should be difference like this x / y , but I couldn't figure it finish it up. 我尝试使用z = random.randint(1, 4)是从1是乘积,2是和或3是差中选择,然后与变量z为1时进行乘积运算,或者如果var z为3,那么应该像x / y那样有所不同,但是我无法确定它是否完成了它。 I have the expected result when I first run with product but it works so I just need to add with sum and difference included. 初次使用产品时,我有预期的结果,但是它可以工作,所以我只需要加上总和和差额即可。

EXPECTED OUTPUT with product ( Some are incorrect for testing with scores ): 产品的预期输出某些分数测试不正确 ):

> 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

My Work for Product Only ( Success ): 我的仅产品工作( 成功 ):

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

My Currently Work: (I am working to add sum and difference like the expected output 我目前的工作:(我正在努力增加总和和差额,如预期的输出

UPDATED : After the expected output works well with product so I am trying to add new random int for z with 1-3 which means I am using with 1 is for product, 2 is for sum and 3 is difference by using if-statement by given random select. 更新 :在预期的输出与产品很好地工作之后,所以我试图为1-3添加z新随机整数,这意味着我使用1表示产品,2表示和,而3表示差异,使用if语句,给定随机选择。 I am struggle at this is where I stopped and figure it out how to do math random because I am new to Python over a month now. 我很努力地在这里停下来,弄清楚如何随机进行数学运算,因为我现在一个月才接触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>

With this currently output, I double checked with corrected Python formatting and everything are sensitive, and still the same as running output. 在当前输出的情况下,我仔细检查了正确的Python格式,所有内容都是敏感的,仍然与运行输出相同。 Any help would be more appreciated with explanation. 任何帮助将通过解释得到更多的赞赏。 (I hope my English is okay to understand since i'm deaf) I have started this since on Saturday, than expected on time to meet. (我希望自从我聋了以后我的英语就可以理解)我从星期六开始,比预期的准时开会。

Your problem is that python 3 does not allow mixing spaces and tabs for indentation. 您的问题是python 3不允许混合空格和制表符用于缩进。 Use an editor that displays the whitespace used (and fix manually) or one that replaces tabs into spaces. 使用一种编辑器来显示使用的空白(并手动修复),或者使用一种将制表符替换为空格的编辑器。 It is suggested to use 4 spaces for indentation - read PEP-0008 for more styling tips. 建议使用4个空格进行缩进-有关更多样式提示,请阅读PEP-0008


You can make your program less cryptic if you use '+','-','*','/' instead of 1,2,3,4 to map your operation: ops = random.choice("+-*/") gives you one of your operators as string. 如果您使用'+','-','*','/'而不是1,2,3,4来映射您的操作,则可以ops = random.choice("+-*/")ops = random.choice("+-*/")作为字符串给您一个运算符。 You feed it into a calc(a,ops,b) function and return the correct result from it. 您将其输入calc(a,ops,b)函数,并从中返回正确的结果。

You can also shorten your askNum and provide the text to print. 您也可以缩短askNum并提供要打印的文本。

These could look like so: 这些可能看起来像这样:

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

Last but not least you need to fix the division part - you allow only integer inputs so you can also only give division problems that are solveable using an integer answer. 最后但并非最不重要的一点是,您需要修复除法部分-您只允许使用整数输入,因此也只能给出使用整数答案可解决的除法问题。

Program: 程序:

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

Output: 输出:

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

Write your block like this your u = askNum() and next if loop should be on same vertical line. 像这样将您的代码块写成u = askNum(),然后将if循环放在同一垂直线上。

To Generate n number of random number you can use 要生成n个随机数,可以使用

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

User this as reference for more info on random 用作参考以获取有关随机的更多信息

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

The following stores a random number(int) 以下存储一个随机数(int)

operator = random.randint(0, 3)

to compare it with the list for operators. 将其与运营商列表进行比较。


Example: operator = 2 示例:operator = 2

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

than this code will executed and because operator=2, 3rd element from list(/) will be selected 将执行此代码,并且因为operator = 2,将选择list(/)中的第三个元素

Output: 输出:

What is 3  / 2?

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

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