TypeError:'str'对象在python 2.7中不可调用

时间:2014-04-05 18:33:10

标签: python python-2.7

程序运行两次然后显示错误

    prize= prize(n,door)
TypeError: 'str' object is not callable.

请帮我处理我的代码,我有什么遗漏吗?

#program to simulate the 3 doors problem using random numbers

from random import *

door= [0 for i in range (3)]
C='y'
count=0
switch=0
noswitch=0
def shuffle():
    doors= [0 for i in range (3)]
    pick= randint(1,3)
    if pick==1:
        doors=['goat', 'goat', 'car']
    elif pick==2:
        doors=['goat', 'car', 'goat']
    else:
        doors = ['car', 'goat', 'goat']
    return doors


def opgoatdoor(n, door):
    for i in range (3):
        while (i+1)!=n and door[i]!= 'car':
                return i+1

def prize(n, door):
    if door[n-1] =='car':
        print '\nCongrats!! You just became the owner of a brand new Rolls Royce!!\n Ride away!'
        return 't'
    else:
        print '\nSorry...guess you are best off with a goat! \n Better luck next time! '
        return 'f'

while C=='y' or C=='Y':
    count+=1
    door= shuffle()
    n= input('Choose a door (1,2,3): ')
    num= opgoatdoor(n, door)
    print ('Lets make this interesting...\n I will reveal a door for you, door no %d holds a Goat!!')  %num
    #print door
    ch= raw_input('\n Now..Do you want to change your choice (press Y) or stick to your previous door(press N)? : ')

    if ch =='y' or ch=='Y':
        n= input('Enter your new door number: ')

        prize= prize(n,door)
        if prize =='t':
            switch+=1

    else:
       prize= prize(n,door)

       if prize =='t':
            noswitch+=1

    C= raw_input('Wanna play again?(Y/N): ')

print 'The no.of times you win a car for %d plays if you switch doors is %d and if you stick with your choice is %d ' %(count, switch, noswitch)

2 个答案:

答案 0 :(得分:3)

您不能将名称prize用于变量和函数;在Python函数中,它们是第一类对象,并且像字符串一样绑定到名称。

您必须重命名其中一个。

或许在prize_won循环中使用while代替:

if ch =='y' or ch=='Y':
    n= input('Enter your new door number: ')

    prize_won = prize(n,door)
    if prize_won == 't':
        switch += 1

else:
    prize_won = prize(n,door)

    if prize_won == 't':
        noswitch += 1

答案 1 :(得分:2)

您在同一范围内定义了两个名为prize的变量,一个字符串和一个函数。

名称的第二个赋值会覆盖第一个,因此prize现在是一个字符串。因此,当您尝试调用函数时,实际上是在尝试调用字符串 - 因此错误。

解决方法是将您的函数或字符串重命名为其他名称。