PyCharm中出现unsupported operand type(s) for +=: 'int' and 'str'错误求助
Fixing the
unsupported operand type(s) for +=: 'int' and 'str' Error in Python Let's break down what's going on and fix this issue quickly:
Why This Error Happens
The problem is straightforward: you're trying to add a string value to an integer variable. Look at your cards list—all elements are string types like '2' or '10'. When you pull DC using random.choice(cards), it’s a string, but PC and CC are integers meant to track score totals. Mixing these incompatible types with the += operator triggers the error you’re seeing.
How to Resolve It
You have two simple, effective ways to fix this:
- Option 1: Convert the string value to an integer immediately after picking it from the list
- Option 2: Define the
cardslist with integer values instead of strings (this is cleaner and avoids repeated conversions)
Corrected Code Examples
Option 1: Convert After Picking the Card
import random # Don't forget this—your original code was missing the random module import! # Initialize score variables as integers PC = 0 CC = 0 nick = "Player" # Make sure to define this variable before using it while True: cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'] DC = random.choice(cards) PC += int(DC) # Convert string to integer before adding to the score card = random.choice(cards) CC += int(card) # Fixed this line—you originally used DC here, which would reuse the same card for both players again = input("again : ") if again == "no": print("Ok") if PC > 21: print("YOU LOSS") elif PC > CC: print("YOU WON") else: print("YOU LOSS") break if PC > 21: print(nick, "LOSE") break
Option 2: Use Integer Values in the cards List
import random PC = 0 CC = 0 nick = "Player" while True: # Define cards with integers instead of strings to skip conversion cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] DC = random.choice(cards) PC += DC # Directly add integers—no conversion needed card = random.choice(cards) CC += card again = input("again : ") if again == "no": print("Ok") if PC > 21: print("YOU LOSS") elif PC > CC: print("YOU WON") else: print("YOU LOSS") break if PC > 21: print(nick, "LOSE") break
Quick Extra Tips
- I added the
import randomline because your original code was missing it—you’d get aNameErrorwithout importing the module first. - I fixed the
CC += DCline toCC += card—otherwise, both players would receive the exact same card every round, which is almost certainly not the behavior you want for a card game.
内容的提问来源于stack exchange,提问作者Mr Pizza
相关产品推荐
相关产品推荐

