如何在python中增加变量整数的值

时间:2018-01-03 21:21:18

标签: python function variables scope override

import re
score = 0

capital_letters = r'[A-Z]'
a = re.compile(capital_letters)

lowercase_letters = r'[a-z]'
b = re.compile(lowercase_letters)

def increase_score (aValue, aScore):
  aScore += aValue
   return aScore

def upper_score(test_string, aScore):
  if re.match(a, test_string):
    aScore = increase_score(5, aScore)
    print (aScore)
    print("UPPERCASE")
  else:
     print("The password needs capital letters for a higher score")


def lower_score(test_string, aScore):
    if re.match(b, test_string):
      aScore = increase_score(5, aScore)
  print (aScore)
  print("LOWERCASE")
else:
  print("The password needs lowercase letters for a higher score")

password = input("Enter a password to check")
upper_score(password, score)
lower_score(password, score)

如果我输入所有大写字母,我会得到这个输出:

5
UPPERCASE

密码需要小写字母才能获得更高分数 如果我输入所有小写字母,我会得到这个输出:

The password needs capital letters for a higher score 
5 
LOWERCASE

当我混合大写和小写时,我得到这个输出:

 5
 UPPERCASE
 5
 LOWERCASE

即使有大写和小写字母,分数仍为5而不是10。

我希望得分能够累积并相互建立。

1 个答案:

答案 0 :(得分:0)

将分数发送到函数时:

upper_score(password, score)

你实际上正在发送一份得分副本。在您的示例中,它接收值为0的score,并创建一个值为0的新变量aScore,因此当您更改aScore时,实际上不会更改{ {1}}。 (小心,即使它们具有相同的名称,它们仍然不会是相同的变量。)

有几种方法可以做你想做的事。 更简单的方法是简单地使函数返回score,然后您可以将其添加到aScore

score