[英]NameError in Credit - pset6 CS50x
I am new to Python.我是 Python 的新手。 My only background in Python is CS50(Week 6).
我在 Python 的唯一背景是 CS50(第 6 周)。 I am trying to implement Credit from pset6.
我正在尝试从 pset6 实施 Credit。 In this, we have to implement Luhn's Algorithm.
在此,我们必须实现 Luhn 算法。
But, I am getting the undermentioned error and I am not able to understand why:但是,我收到了下面提到的错误,我不明白为什么:
Traceback (most recent call last):
File "credit.py", line 57, in <module>
main()
File "credit.py", line 9, in main
if IfAmex(arr_number):
File "credit.py", line 27, in IfAmex
if Luhn(card_n):
File "credit.py", line 50, in Luhn
sum2 = sum(int(c) for c in str(2 * card_n[i]) for i in range(1, len(card_n), 2))
NameError: name 'i' is not defined
Here is my code:这是我的代码:
from sys import exit
from cs50 import get_int
def main():
number = get_int("Number: ")
# Converting the number into a list
arr_number = [int(x) for x in str(number)]
if IfAmex(arr_number):
print("AMEX")
exit(0)
elif IfMasCard(arr_number):
print("MASTERCARD")
exit(0)
elif IfVisa(arr_number):
print("VISA")
exit(0)
else:
print("INVALID")
exit(0)
def IfAmex(card_n):
if not len(card_n) == 15:
return False
if not (card_n[0] * 10 + card_n[1]) in [34, 37]:
return False
if Luhn(card_n):
return True
def IfMasCas(card_n):
if not len(card_n) == 16:
return False
if not (card_n[0] * 10 + card_n[1]) in range(51, 56):
return False
if Luhn(card_n):
return True
def IfVisa(card_n):
if not len(card_n) in [13, 16]:
return False
if not card_n[0] == 4:
return False
if Luhn(card_n):
return True
def Luhn(card_n):
# Reversing the digits
card_n = card_n[::-1]
sum1 = sum(card_n[::2])
sum2 = sum(int(c) for c in str(2 * card_n[i]) for i in range(1, len(card_n), 2)) # The Error Line
luhnsum = sum1 + sum2
return luhnsum % 10 == 0
if __name__ == '__main__':
main()
And the test case I used was(along with the correct output):我使用的测试用例是(以及正确的输出):
$ python credit.py
Number: 378282246310005
AMEX
Also, please tell me whether I am using exit()
correctly or not.另外,请告诉我我是否正确使用了
exit()
。
You use i
here as an index of card_n array.您在这里使用
i
作为 card_n 数组的索引。 But you forgot to define it.但是你忘了定义它。
Define it and assign it to a value before using.在使用之前定义它并为其分配一个值。
sum2 = sum(int(c) for c in str(2 * card_n[i])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.