【发布时间】:2021-12-17 04:46:50
【问题描述】:
我想首先说我在 Python 方面处于非常初级的水平,并且可能还没有以最有效的方式编写代码。
我正在尝试构建一个程序,为用户提供一个简单的数学测验。它随机选择一个问题(加法、减法、除法或乘法)并要求用户输入以回答问题。
如果用户做对了,我要祝贺他们。如果他们弄错了,我想给他们正确的答案。我为我想给用户的每种不同类型的问题制作了函数,并将它们添加到列表中。然后我随机选择了一个要调用的函数并提供给用户。
从这里开始,我想我只需将一个变量 (prob) 分配给随机选择的函数,并将其用作一系列 if else 语句中的条件。这行不通。相反,它会跳过我希望它发回给他们的消息,然后转到我的下一个input 命令。我猜是因为我不能真正为随机选择函数分配一个变量。
否则我将如何编写代码以使其执行我希望它执行的操作?
import random
def problem():
global add
def add():
num1 = random.randint(0, 999)
num2 = random.randint(0, 999)
global addition
addition = num1 + num2
op1 = f' {num1}\n+{num2}'
print(op1)
global sub
def sub():
num1 = random.randint(0, 999)
num2 = random.randint(0, 999)
global subtract
subtract = num1 - num2
op2 = f' {num1}\n-{num2}'
if subtract < 0:
sub()
elif subtract > 0:
print(op2)
global mult
def mult():
num1 = random.randint(1, 12)
num2 = random.randint(1, 12)
global multiply
multiply = num1 * num2
op3 = f'{num1} * {num2}'
print(op3)
global div
def div():
num1 = random.randint(0, 150)
num2 = random.randint(0, 150)
global divide
divide = num1 / num2
op4 = f'{num1} / {num2}'
if num1 % num2 == 0:
print(op4)
elif num1 % num2 != 0 or num2 == 0:
div()
global numlist
numlist = [add, sub, mult, div]
prob = random.choice(numlist)()
answer = input()
if prob == numlist[0] and answer == f'{add.addition}':
print(f'Congrats! You got it right.')
elif prob == numlist[0] and answer != f'{add.addition}':
print(f'Incorrect. The answer is {add.addition}.')
elif prob == numlist[1] and answer == f'{sub.subtract}':
print(f'Congrats! You got it right.')
elif prob == numlist[1] and answer != f'{sub.subtract}':
print(f'Incorrect. The answer is {sub.subtract}.')
elif prob == numlist[2] and answer == f'{mult.multiply}':
print(f'Congrats! You got it right.')
elif prob == numlist[2] and answer != f'{mult.multiply}':
print(f'Incorrect. The answer is {mult.multiply}.')
elif prob == numlist[3] and answer == f'{div.divide}':
print(f'Congrats! You got it right.')
elif prob == numlist[3] and answer != f'{div.divide}':
print(f'Incorrect. The answer is {div.divide}.')
done = input('Type "done" if you want to be done. Press Enter if you want another problem.\n')
while done == '':
problem()
if done == 'done' or done == 'Done':
break
problem()
【问题讨论】:
-
您应该只访问
additionsubstractionmultiplication和division的名称,而不是add.addition...
标签: python function if-statement random