random.choice - TypeError:'method'对象不可订阅

时间:2014-11-28 11:46:51

标签: python

我的评估任务要求我们创建一个程序,询问10个随机生成的问题;由减法/多重/加法组成,我已经完成了随机生成的问题的代码,但我不明白为什么会出现同样的错误,请有人看一看,错误是:

Traceback (most recent call last):
  File "N:\Open Me x\Computing\Mrs Farakh\Programming\Python\srg.py", line 71, in <module>
    random.choice[(add(),mult(),subtr())]
TypeError: 'method' object is not subscriptable

代码是:

import random
import time
global y
y = 0

name = input("Please enter your name: ")
time.sleep(1)
print("You will be prompted 10 mathmatical questions to answer, try your best. If you need help please ask your teacher for an explination on what the task is. Goodluck",name,"!")

def mult():
    global y 
    rand1 = random.randint(2,16)
    rand2 = random.randint(2,16)
    print("What is",rand1,"*", rand2,"?")
    x = int(input())
    ans = rand1 * rand2
    if x == ans:
        print("Correct: You gain 1 point!")
        y = y + 1
        print (y)
    elif x != ans:
        print("You, gain no points")
        y = y * 1
        print(y)
        print("Incorrect")
    else:
        print("Next question")

def subtr():
    global y 
    rand1 = random.randint(2,16)
    rand2 = random.randint(2,16)
    print("What is",rand1,"-", rand2,"?")
    x = int(input())
    ans = rand1 - rand2
    if x == ans:
        print("Correct: You gain 1 point!")
        y = y + 1
        print (y)
    elif x != ans:
        print("You, gain no points")
        y = y * 1
        print(y)
        print("Incorrect")
    else:
        print("Next question")

def add():
    global y 
    rand1 = random.randint(2,16)
    rand2 = random.randint(2,16) 
    print("What is",rand1,"+", rand2,"?")
    x = int(input())
    ans = rand1 + rand2
    if x == ans:
        print("Correct: You gain 1 point!")
        y = y + 1
        print (y)
    elif x != ans:
        print("You, gain no points")
        y = y * 1
        print(y)
        print("Incorrect")
    else:
        print("Next question")




for x in range(10):
    random.choice[(add(),mult(),subtr())]

if y == 10:
    print("Congratulations" ,name, "you have gotten all the questions correct; thanks for taking part.")
else:
    print("Thanks for taking part", name)

很抱歉,我现在再次成为python的一个不成熟的人,所以如果你能帮助我理解为什么错误发生同时回答我的问题,那将是非常的有帮助:))

编辑:

抱歉,我忘了说,当subtr函数发生时,错误发生,其他函数正常工作..

2 个答案:

答案 0 :(得分:2)

random.choice函数,您需要使用列表(或其他集合)调用它。

此外,您不能将函数调用放在该列表中,因为这将首先调用所有三个函数,然后调用random.choice

相反,将函数(未调用)放入列表中,将该数组传递给random.choice,然后调用生成的(随机选择的)函数:

possible_choices = [add, mult, subtr]
choice = random.choice(possible_choices)
choice()

choice是随机选择的函数,因此我们可以调用它。但是,很多人会觉得这段代码过于冗长,因为它不必要地创建了中间变量。您可以将整个逻辑放在一个表达式中:

random.choice([add, mult, subtr])()

答案 1 :(得分:-1)

这是问题所在:

random.choice[(add(),mult(),subtr())]

替换为:

random.choice((add(),mult(),subtr()))