python - Python在函数内部更改变量值时不保存变量值
问题描述
我在程序开始时保存了我的变量并允许函数访问它们我相信但是当它们运行时,当函数重复时不会保存值。
P1_score = 0
P2_score = 0
round_number = 0
def dice_rolling():
# P1D1 means player ones dice one value and so on with P1D2
import random
# player ones turn
print("player ones turn")
P1D1 = random.randint(1, 6)
print("your number is ", P1D1)
P1D2 = random.randint(1, 6)
print("your second number is", P1D2)
# player twos turn
print("player twos turn")
P2D1 = random.randint(1, 6)
print("your number is", P2D1)
P2D2 = random.randint(1, 6)
print("your second number is", P2D2)
score_calculation(P1D1, P1D2, P2D1, P2D2,P1_score,P2_score,round_number)
def score_calculation(P1D1, P1D2, P2D1, P2D2,P1_score,P2_score,round_number):
import random
round_number = round_number + 1
# player 1 score calculation
total_P1 = P1D1 + P1D2
P1_score = P1_score + total_P1
if total_P1 % 2 == 0:
P1_score = P1_score + 10
else:
P1_score = P1_score + 5
if P1D1 == P1D2:
P1D3 = random.randint(1, 6)
P1_score = P1_score + P1D3
# player 2 score calculation
total_P2 = P2D1 + P2D2
P2_score = P2_score + total_P2
if total_P2 % 2 == 0:
P2_score = P2_score + 10
else:
P2_score = P2_score + 5
if P2D1 == P2D2:
P2D3 = random.randint(1, 6)
P2_score = P2_score + P2D3
print("player ones score at the end of round", round_number, "is", P1_score)
print("player twos score at the end of round",round_number,"is",P2_score)
for x in range(0,5):
dice_rolling()
任何帮助将不胜感激,如果有人可以简单地解释我做错了什么以及要解决什么问题,那就太好了。
解决方案
Python 可以从函数内部的全局变量中读取,但如果没有一些额外的工作就无法分配它们。global
通常,当您想使用全局变量时,最好通过在函数中使用关键字来使其显式化:
my_global_var = 0
def some_function():
global my_gobal_var
my_global_var = 10
print(my_global_var) # it prints 10
somefunction() # modifies the global var
print(my_global_var) # now it prints 10
推荐阅读
- excel - Vlookup 公式显示 1004 错误。解决方法也失败了
- java - java.lang.ClassNotFoundException: com.mysql.idbc.Driver 问题
- proxy - 如何在不更改名称服务器的情况下使用 cloudflare
- html - 选择子元素 css
- sql - Update Table from another Table in SQL Server 2016, plus "could not be bound" issue
- mongoose - Mongoose query on last item in array
- pandas - 熊猫系列元素的成对最小值
- python - Python 使用 setup.py 手动将包安装到虚拟环境
- c# - State Error CS0501 'MoviesController.Random()' must declare a body because it is not marked abstract, extern, or partial WebApplication1
- android - How to close simple light box written by Animations on react native