How can i fixTypeError: 'str' object is no

2019-02-21 04:49发布

问题:

Well i've seen this error occur to others aswell but i can't figure out were my mistake is.

I get this:

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

Here is my code: (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))`

It is a simple blackjack game that most beginners make in python i hope that the comments on the code will help you understand it.

My mistake should be something silly as long as i am new to the language but i hope you will help me. It runs as it should the only problem is... When the programm asks :

Start new game (n) or continue previous game (c)?

and you give 'c' as input it gives the error.

I found this method on this site so i may not use it right:

combined = list(zip(symbols,deck))
shuffledDeck(combined)
symbols[:], deck[:] = zip(*combined)
  • any improvements to the code are acceptable.

Thanks in Advance!

UPDATE!

is there any way to display the letter 'A' (stands for ace) instead of 11?

eg.

You got A ♡ instead of

You got 11 ♡

回答1:

You've overwritten the built-in list function with a string:

list=l.pop()

To fix this, use a different variable name, other than list. In general, you'll want to avoid shadowing built-ins when naming your variables. That is, don't name things list, map, dict, etc.

It's also good practice to name your variables after what's in them. So if you have list = ["apples", "oranges", "pears"], you might consider renaming it fruits = ["apples", "oranges", "pears"]. It really helps with code readability.



回答2:

You've defined list to be a string:

list=l.pop()

So

list(zip(symbols,deck))

causes Python to complain that list is not callable.

The solution, of course, is to use descriptive variable names that do not shadow Python builtins.



回答3:

This happened to me recently where I tried to call a function I had defined from within another function, but didn't notice that I also had a local variable in the calling fucntion with the same name as the function I was trying to call.

Due to the scope rules the call to the function was being interpreted as calling the local variable...hence the error message since a scalar variable of type 'str' (for example) is not callable.

So the essence of the problem is variables sharing the names of functions you need to call within their scope, whether they be functions you've defined, those included in imported modules or Python built-ins.