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

问题描述 投票:-1回答:1

这个问题在这里已有答案:

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。

我希望得分是累积的,并且建立在彼此之上。

python function variables scope override
1个回答
0
投票

将分数发送到函数时:

upper_score(password, score)

你实际上正在发送一个分数的副本。在你的例子中,它接收值为0的score,并创建一个值为0的新变量aScore,所以当你改变aScore时,你实际上并没有改变score。 (注意,即使它们具有相同的名称,它们仍然不会是相同的变量。)

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

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")
  return aScore


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")
    return aScore

password = input("Enter a password to check")
score += upper_score(password, score)
score += lower_score(password, score)
print("total score: " + score)
© www.soinside.com 2019 - 2024. All rights reserved.