繁体   English   中英

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

[英]TypeError: 'str' object is not callable in 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)

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

您必须重命名一个或另一个。

也许在while循环中使用prize_won

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

您在相同的作用域中定义了两个名为prize变量,即字符串和函数。

名称的第二个分配优先于第一个,因此prize现在是字符串。 因此,当您尝试调用函数时,实际上是在尝试调用字符串,因此会出现错误。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM