英文:
Not understanding error: "local variable 'computer_total' referenced before assignment when it is not? (I could be wrong)
问题
抱歉,以下是您提供的代码的翻译部分:
请原谅我的语法或沟通,我是StackOverflow的新手。我正在构建以下代码,但我遇到了以下错误:
> 追踪(最近的调用最后一次):
> 文件“main.py”,第58行,在<module>中:
> add_total_c()
> 文件“main.py”,第43行,在add_total_c中:
> computer_total += computers_card[total_c]
> UnboundLocalError:在赋值之前引用本地变量'computer_total'
我理解这意味着我试图在调用之前引用一个变量。但这对我来说没有意义,因为**computer_total**是在内存中设置后再引用的。我已经用粗体标出了特定的代码以供视觉参考。在我的想法中,首先列出上面的变量允许引用下面的代码。但是出于某种原因,当调用函数时,它似乎认为变量不存在?
请让我知道您的想法以及如何解决。如果有示例的话,我更喜欢示例。
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computers_card = []
user_card = []
computer_total = 0 # 这里
user_total = 0
def deal_computer():
for c_card in range (1, 3):
computers_card.append(cards[random.randint(0, len(cards)))]
def deal_user():
for u_card in range (1, 3):
user_card.append(cards[random.randint(0, len(cards)))]
def initial_cards():
deal_computer()
deal_user()
def add_total_c():
for total_c in range(0,len(computers_card)):
computer_total += computers_card[total_c] # <--
def add_total_u():
for total_u in range(0, len(user_card)):
user_total += user_card[total_u]
print(f"Your cards: {user_card}")
print(f"Computer's first cards: {computers_card}")
initial_cards()
choice = input("Type 'y' for another card or 'n' to stand with your current cards")
if choice == "n":
add_total_c()
add_total_u()
stand = True
while stand:
if computer_total > 17 and computer_total < 21:
if user_total > computer_total:
print("You Won!")
stand = False
else:
print("you lose!")
stand = False
if computer_total < 17:
computers_card.append(cards[random.randint(0, len(cards))])
add_total_c()
if computer_total > 21:
print("Computer Bust")
<details>
<summary>英文:</summary>
Excuse my syntax or communication I am new to stackoverflow. I am building the below code and I am getting an error that states the following:
> Traceback (most recent call last):
> File "main.py", line 58, in <module>
> add_total_c()
> File "main.py", line 43, in add_total_c
> computer_total += computers_card[total_c]
> UnboundLocalError: local variable 'computer_total' referenced before assignment
I understand that it means I am trying to reference a variable before its being called out. but that doesn't make sense to me because **computer_total** is being referenced after the variable has been set in memory. I have bold specific code below for visual. In my head I feel that having the variables listed above first allows the below code to be referenced. but for some reason when calling the function it feels the variable doesn't exist?
please let me know what you think and how to solve. I prefer examples if available.
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computers_card = []
user_card = []
computer_total = 0 # Here
user_total = 0
def deal_computer():
for c_card in range (1, 3):
computers_card.append(cards[random.randint(0, len(cards))])
def deal_user():
for u_card in range (1, 3):
user_card.append(cards[random.randint(0, len(cards))])
def initial_cards():
deal_computer()
deal_user()
def add_total_c():
for total_c in range(0,len(computers_card)):
computer_total += computers_card[total_c] # <--
def add_total_u():
for total_u in range(0, len(user_card)):
user_total += user_card[total_u]
print(f"Your cards: {user_card}")
print(f"Computer's first cards: {computers_card}")
initial_cards()
choice = input("Type 'y' for another card or 'n' to stand with your current cards")
if choice == "n":
add_total_c()
add_total_u()
stand = True
while stand:
if computer_total > 17 and computer_total < 21:
if user_total > computer_total:
print("You Won!")
stand = False
else:
print("you lose!")
stand = False
if computer_total < 17:
computers_card.append(cards[random.randint(0, len(cards))])
add_total_c()
if computer_total > 21:
print("Computer Bust")
I have tried to placed the variables inside the functions so that the reference is available when that function code is needed. unfortunately that creates problems when I later have to reference that code again.
</details>
# 答案1
**得分**: 2
问题是*computer_total*变量在*add_total_c()*函数外部定义,但当您尝试在函数内部修改它时,Python会将其视为函数范围内的局部变量。要解决此问题,您需要明确告诉Python使用全局变量*computer_total*,而不是创建一个新的局部变量。
您可以像这样修改并使用*global*关键字:
```python
def add_total_c():
global computer_total # 使用全局的computer_total变量
for total_c in range(len(computers_card)):
computer_total += computers_card[total_c]
英文:
The issue is that the computer_total variable is defined outside the add_total_c() function, but when you try to modify it inside the function, Python considers it a local variable within the function's scope. To solve this, you need to explicitly tell Python to use the global variable computer_total instead of creating a new local one.
You can modify and use global keyword like this:
def add_total_c():
global computer_total # Use the global computer_total variable
for total_c in range(len(computers_card)):
computer_total += computers_card[total_c]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论