为什么打印0而不是5? 我无法在逻辑中找到错误?
score = 0
def pass_score(test_string, aScore):
if re.match(a, test_string):
increase_score(5, score)
print (aScore)
def increase_score (aValue, aScore):
aScore += aValue
答案 0 :(得分:2)
第一种方法,没有全局变量,返回值:
def increase_score (aValue, aScore):
aScore += aValue
return aScore
def pass_score(test_string, aScore):
if re.match(a, test_string):
aScore = increase_score(5, aScore)
print (aScore)
第二种方法,使用global var:
score = 0
def increase_score (aValue): #don't need to receive score, I've it.
global score
score += aValue
def pass_score(test_string):
global score
if re.match(a, test_string):
increase_score(5)
print (score)
我想你需要两者兼而有之。无论如何,此时你的代码看起来有点脏,混合了本地和全局变量。
答案 1 :(得分:1)
你可以做全局,但不要。相反,返回值。
def increase_score (aValue, aScore):
return aScore += aValue
def pass_score(test_string, aScore):
if re.match(a, test_string):
aScore += increase_score(5, aScore)
print (aScore)