从lis中随机选取子例程

2024-04-28 19:58:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这是针对python3.3的。当我运行这个程序时,它总是运行子程序“func\u 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))

Tags: answernameinputismydefrandomwhat
2条回答

删除paren,否则在创建列表时将调用所有函数。你知道吗

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))
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] #without parentheses

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

相关问题 更多 >