gpt4 book ai didi

python - 从列表中随机选择子例程

转载 作者:行者123 更新时间:2023-11-30 23:18:29 24 4
gpt4 key购买 nike

这是针对 Python 3.3 的。当我运行这个程序时,它总是运行子例程“func_addition”。

我想让它从列表中随机选择一个子例程。因此,它会问一个随机算术问题。

import random
def func_addition():
a = random.randint(1,25)
b = random.randint(1,25)
c=a+b
answer=int(input("What is "+str(a)+" + "+str(b)+" ? "))

def func_subtraction():
d = random.randint(10,25)
e = random.randint(1,10)
f=d-e
answer=int(input("What is "+str(d)+" - "+str(e)+" ? "))

def func_multiplication():
g = random.randint(1,10)
h = random.randint(1,10)
i=g*h
answer=int(input("What is "+str(g)+" X "+str(h)+" ? "))

my_list=[func_addition() , func_subtraction() , func_multiplication()]

name=input("What is your name ? ")
print("Hello "+str(name)+" and welcome to The Arithmetic Quiz")
print(random.choice(my_list))

最佳答案

删除括号,否则您将在创建列表时调用所有函数。

my_list = [func_addition , func_subtraction , func_multiplication]

name = input("What is your name ? ")
print("Hello {} and welcome to The Arithmetic Quiz".format(name))
chc = random.choice(my_list) # pick random function
chc() # call function

您没有看到使用变量,我会执行以下操作来验证答案:

def func_addition():
a = random.randint(1,25)
b = random.randint(1,25)
c = a + b
answer = int(input("What is {} + {} ? ".format(a,b)))
if answer == c:
print("Well done, that is correct")
else:
print(" Sorry, that is incorrect, the correct answer is {}".format(c))

关于python - 从列表中随机选择子例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26738419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com