python - 如何在Python中使用def和参数

标签 python function parameters

为什么它打印 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

最佳答案

第一种方法,没有全局变量,返回值:

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变量:

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)

我想你需要两者的结合。无论如何,您的代码此时看起来有点脏,混合了本地变量和全局变量。

关于python - 如何在Python中使用def和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48052710/

相关文章:

Python ElementTree xml 输出到 csv

python pymysql设置autocommit false失败

c - 使用 while 循环计算数字的平方根的近似值

parameters - 如何在 Alamofire, swift 3 中将字典作为参数发送

java - 忽略参数的方法

arrays - 奇怪的行为:输入参数(具有以 “D”或 “L”字符结尾的多个值)

python - SQLAlchemy 默认的 PostgreSQL ARRAY 行为

python - 按特定列对矩阵进行排序(具有 2 位或更多数字)

javascript - 我的下拉菜单显示完全不工作

c - 这个c程序编译运行后出现未知错误