[英]UnboundLocalError: local variable 'sumOfOdd' referenced before assignment in Python3
I'm trying to run this code:我正在尝试运行此代码:
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
def main():
print(f"Your credit card number is {number}, it's third digit is {number[2]}")
print(f'sum of odds: {sumOfOdd}')
validation(number)
main()
But I get this error:但我得到这个错误:
Traceback (most recent call last):
File "credit.py", line 15, in <module>
validation(number)
File "credit.py", line 8, in validation
sumOfOdd += i
UnboundLocalError: local variable 'sumOfOdd' referenced before assignment
I'm able to run, but when I input any number it gives me this error我可以运行,但是当我输入任何数字时,它会给我这个错误
This error occurs because the variable sumOfOdd
is not accessible from within the function.发生此错误是因为无法从 function 中访问变量
sumOfOdd
。 You could declare the variable global
in the function , but you should be careful using the global
statement.您可以在 function 中声明变量
global
,但使用global
语句时应小心。
In my opinion, a better way to do this is to supply sumOfOdd
as an argument to the function and return the updated variable:在我看来,更好的方法是将
sumOfOdd
作为参数提供给 function 并返回更新后的变量:
def validation(credit_num, sumOfOdd):
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
return sumOfOdd
validation(number, 0)
# Returns the correct sum.
Or, if you know that the sumOfOdd
should always be initialized by zero, you could define the variable locally:或者,如果您知道
sumOfOdd
应始终初始化为零,则可以在本地定义变量:
def validation(credit_num):
sumOfOdd = 0
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
return sumOfOdd
Here's a working version of your code.这是您的代码的工作版本。
Note that it now iterates through credit_num
as for num in credit_num
.请注意,它现在遍历
credit_num
,就像 credit_num 中for num in credit_num
。 If you use for i in range(len(credit_num))
you are iterating through a list of indexes and would need to use if int(credit_num[i]) % 2 != 0
, reason being that range(N)
returns a list [0, 1, 2... N-1]
where for num in credit_num
iterates through [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4]
if your input string was 1111222233334444
如果您使用
for i in range(len(credit_num))
您正在遍历索引列表并且需要使用if int(credit_num[i]) % 2 != 0
,原因是range(N)
返回一个列表[0, 1, 2... N-1]
其中for num in credit_num
遍历[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4]
如果您的输入字符串是1111222233334444
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
global sumOfOdd
for num in credit_num:
if int(num) % 2 != 0:
sumOfOdd += 1
def main():
print(f"Your credit card number is {number}, it's third digit is {number[2]}")
print(f'sum of odds: {sumOfOdd}')
validation(number)
main()
Note that validation(number)
is called in global scope along with main()
, hence the global sumOfOdd
declaration inside to allow def validation
to gain access to that variable.请注意,
validation(number)
与main()
一起在全局 scope 中调用,因此内部的global sumOfOdd
声明允许def validation
访问该变量。
A different way to write this code to make it more readable would be:编写此代码以使其更具可读性的另一种方法是:
if __name__ == "__main__":
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
sumOfOddToReturn = 0
for num in credit_num:
if int(num) % 2 != 0:
sumOfOddToReturn += 1
return sumOfOddToReturn
sumOfOdd = validation(number)
print(f"Your credit card number is `{number}`, its third digit is `{number[2]}`.")
print(f'sum of odds: {sumOfOdd}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.