【问题标题】:How can i fixTypeError: 'str' object is not callable?如何修复 TypeError:'str' 对象不可调用?
【发布时间】:2015-02-15 11:07:46
【问题描述】:

好吧,我也看到其他人也发生过这个错误,但我不知道是我的错误。

我明白了:

Traceback (most recent call last):
File "C:\Users\Bill\Desktop\Finalizing_2.1(DEVELOPING).py", line 100, in <module>
combined = list(zip(symbols,deck))
TypeError: 'str' object is not callable

这是我的代码:(Python 3.x)

import random #shuffle
import os#file deleting

def shuffledDeck(deck):#shuffles ceck
    random.shuffle(deck)

def dealCard(deck,participant):#deal cards , chooses between player and house with string z
    participant.append(deck.pop())
    if z==1:
        print('\nYou got  %s ' %("{} {}".format(player[len(player)-1],symbols.pop()))) 
    else:
        print('\nHouse got %s ' %("{} {}".format(house[len(house)-1],symbols.pop())))

def total(hand):#chooses between player and house with string z and displays total
    y =sum(hand)
    if z==1:
        print('Your total now is :',y)
    else:
        print('House total now is :',y)

def compareHands(house, player):  #compares players and house's hand totals
    global wallet 
    global bet
    global bank
    if sum(house)>sum(player):
        print('You Lose :(')

        wallet += bet
        bank -= bet
        prw = False
    elif sum(house)<sum(player):
        print('You Win!')

        wallet += bet
        bank -= bet
        prw = True
    elif sum(house)==sum(player):
        print('DRAW!')

def printHistory(history):  #  prints history.txt
    if history=='h':
        f = open('history.txt')
        for l in f:
            print(l,end='') 


# r=0           # last game
row = 1         #  times a game was played
bank = 10       # starting value
exit = False    # making sure the game won't exit if the user doesn't want to
newGame = True

#  defy if it is a new game or the previous had been canceled
try:
   f=open('history.txt')
   print('\n________________________ \nHistory File Available')
   newGame=False#it is not a new game
except FileNotFoundError:
    print('Creating History File..')
    f=open('history.txt','w')
    newGame=True#it is a new game
if newGame==False:#if it is not a new game
    answer=input('Start new game (n) or continue previous game (c)?')#ask 
    if answer=='n':
        f.close()
        os.remove('history.txt')
        f=open('history.txt','w')
    elif answer=='c':
        f=open('history.txt')
        l=f.readlines()
        list=l.pop()
        splitlist=list.split()
        row=int(splitlist[0])
        bank=int(splitlist[5])

print('========================')#begining game

Done=iter([True, False])
while bank>0 and exit==False and (bank <30 or next(Done)):#if bank<0 bank looses so the loop brakes


deck=[2,2,2,2,3,3,3,3,4,4,4,4,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11]
symbols=['\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663']


wallet = 0 #Money player won
prw = False #Player Won
player = []
house = []
bet = 0
z = 1 #to choose player or house in totalHand()
loop = True #Enter Houses loop
#out2=1#loopbrake2
Round = 2 #Rounds played(used in 5 cards combination)


#  shuffle both deck and symbols the same way
combined = list(zip(symbols,deck))
shuffledDeck(combined)
symbols[:], deck[:] = zip(*combined)

#player
dealCard(deck,player)
bet = int(input('Place your bet: '))
while bet > bank:
    print('Your bet should not be higher than bank\nplease try again >>>')
    bet = int(input('Place your bet: '))
dealCard(deck,player)
total(player)


#checking
if sum(player) == 22: #double ace
    print('You win (Α-Α)!!')

    wallet += bet
    bank -= bet
    loop = False
    prw = True
elif sum(player)==21:
    print('You win!!')

    wallet += bet
    bank -= bet
    loop = False
    prw = True
else:
    action = input('Hit (h) or stand (s)?: ')
    while action == 'h' and sum(player) <= 21 and prw == False:
        dealCard(deck, player)
        total(player)
        Round += 1     # 5 cards combination

        if player[0] == 7 and player[1] == 7 and player[2] == 7:
            print('You win (Σκουπα)!!')

            wallet += bank
            bank -= bank
            loop = False
            prw = True
            exit = True
        elif Round == 5 and sum(player) <= 21:
            print('You win! (Πενταφυλλια)')

            wallet += bet
            bank -= bet
            loop = False
            prw = True
        elif sum(player) == 21:
            print('You win (21)!!')

            wallet += bet
            bank -= bet
            loop = False
            prw = True
        elif sum(player) < 21:
            action = input('Hit (h) or stand (s)?: ')
        elif sum(player) > 21:
            print('You Lose :( ')

            wallet -= bet
            bank += bet
            loop = False
            pwd = False




#houses turn
if loop is True:
    z=0
    dealCard(deck,house)

    total(house)
    while sum(house)<17:
        dealCard(deck,house)
        total(house)


    #comparison
    if sum(house)<=21:
        if house[0] == 7 and house[1] == 7 and house[2] == 7:
            print('You Lose :( (7-7-7)')

            wallet = 0
            bank += bet
            pwd = False
            exit = True         
        elif sum(house) == 21:
            print('You Lose :( ')

            wallet -= bet
            bank += bet
            pwd = False
        else:
            compareHands(house,player)
    elif sum(house)>21:
        print('You Win!')

        wallet += bet
        bank -= bet
        prw = True

print("Bank's balance now is", bank)
if sum(house) == sum(player):
    winner = 'DRAW'
elif prw is False:
    winner = 'House'
elif prw is True:
    winner = 'Player'


#updating history.txt file
if row==1:
    f=open('history.txt','r+')
    f.write('%-*s%-*s%-*s%-*s%-*s %-*s'%  (10,'Round',15,'Bet($)',10,'Player',10,'House',15,'Winner',10,'Bank($)'))
    f.close()
    f=open('history.txt','a')
    f.write('\n%-*s%-*s%-*s%-*s%-*s %-*s'%(10,row,15,bet,10,sum(player),10,sum(house),15,winner,10,bank))
    row+=1
    f.close()
else:
    f=open('history.txt','a')
    f.write('\n%-*s%-*s%-*s%-*s%-*s %-*s'%      (10,row,15,bet,10,sum(player),10,sum(house),15,winner,10,bank))
    row+=1
    f.close()


#display history and other actions
history=input('\nContinue(c), print history (h) or exit game (x)?')
while history=='h':
    printHistory(history)
    history=input('\nContinue(c), print history (h) or exit game (x)?')
if history=='c':
    exit=False
else:
    exit=True


#game overview
print('Game Over')
if bank==0:
    print('Player has won $10')
elif bank>10:
    print('Player has lost %d$'%(bank-10))`

这是一个大多数初学者用python制作的简单的二十一点游戏,希望代码上的cmets能帮助你理解它。

只要我是语言新手,我的错误应该是愚蠢的,但我希望你能帮助我。 它按照它应该运行的方式运行,唯一的问题是...... 当程序询问时:

开始新游戏 (n) 还是继续上一游戏 (c)?

你输入 'c' 作为输入,它给出了错误。

我在这个网站上找到了这个方法,所以我可能不会正确使用它:

combined = list(zip(symbols,deck))
shuffledDeck(combined)
symbols[:], deck[:] = zip(*combined)
  • 对代码的任何改进都是可以接受的。

提前致谢!

更新!

有什么方法可以显示字母“A”(代表 ace)而不是 11?

例如。

你有一个♡ 而不是

你有 11 个♡

【问题讨论】:

  • 我只想在名为 suffledDeck() 的函数上提名“#shuffles deck”,该函数的单行代码为 random.shuffle(deck),是有史以来最没用的评论。 :-)

标签: python list python-3.x zip blackjack


【解决方案1】:

您已经用字符串覆盖了内置的list 函数:

list=l.pop()

要解决此问题,请使用除 list 之外的其他变量名称。通常,在命名变量时,您会希望避免隐藏内置函数。也就是说,不要将事物命名为listmapdict 等。

根据变量中的内容命名变量也是一种很好的做法。所以如果你有list = ["apples", "oranges", "pears"],你可以考虑将它重命名为fruits = ["apples", "oranges", "pears"]。它确实有助于提高代码的可读性。

【讨论】:

  • @Bill 当然,您不仅要在那个地方更改名称 list
  • 是的,我知道!每次我都用过列表
【解决方案2】:

您已将list 定义为字符串:

list=l.pop()

所以

list(zip(symbols,deck))

导致 Python 抱怨 list 不可调用。

当然,解决方案是使用不影响 Python 内置函数的描述性变量名称。

【讨论】:

  • 好吧,我做到了!我不知道列表是这样工作的,但我应该想到我因为它在崇高的文本中突出显示为蓝色!
【解决方案3】:

这件事最近发生在我身上,我试图调用我在另一个函数中定义的函数,但没有注意到我在调用函数中还有一个与我试图调用的函数同名的局部变量称呼。

由于作用域规则,对函数的调用被解释为调用局部变量...因此错误消息是因为“str”类型的标量变量(例如)不可调用。

所以问题的本质是变量共享您需要在其范围内调用的函数的名称,无论它们是您定义的函数、包含在导入模块中的函数还是 Python 内置函数。

【讨论】:

    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 2015-03-07
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2020-09-16
    相关资源
    最近更新 更多