CS50 credit.py 试图通过转换为整数来添加字符串的总和
CS50 credit.py attempting to add the sum of an string by converting to integer
有人可以为我指出有关我的 sum1 变量的正确方向吗?
我正在尝试从变量doubled 中存储doubled nums 的值。
在我看来,我正在执行与获取双变量相同的操作,但当我尝试打印调试时,这显然行不通。这是我第一次涉足 python。
对于我一直在输入的卡:1234567890987
我了解错误,但不知道如何解决。我将不胜感激任何反馈或指示
感谢您的时间和努力
from cs50 import get_int, get_string
def main():
# get an integer from the user to ensure only int imputs
card = get_int("Card: ")
# convert the card into a string so it may be indexed to manipulate individual digits
card = str(card)
# check len to make sure its the correct amount of numbers that would be in a major credit card.
if len(card) < 13 or len(card) > 16:
print("invalid len")
exit(1)
# iterate over every other number in the card starting with the second to last digit
for i in range(len(card)-2, 0, -2):
doubled = (int(card[i]) *2)
#add the string values together
sum1 = sum(int(doubled))
print(sum1)
main()
终端显示:
Traceback (most recent call last):
File "/home/ubuntu/pset6/credit/credit.py", line 22, in <module>
main()
File "/home/ubuntu/pset6/credit/credit.py", line 20, in main
sum1 = sum(int(doubled))
TypeError: 'int' object is not iterable
sum()
函数需要一个迭代器,而您给它一个 integer
。也许你正在尝试使用 sum1 += int(doubled)
.
有人可以为我指出有关我的 sum1 变量的正确方向吗?
我正在尝试从变量doubled 中存储doubled nums 的值。 在我看来,我正在执行与获取双变量相同的操作,但当我尝试打印调试时,这显然行不通。这是我第一次涉足 python。 对于我一直在输入的卡:1234567890987 我了解错误,但不知道如何解决。我将不胜感激任何反馈或指示 感谢您的时间和努力
from cs50 import get_int, get_string
def main():
# get an integer from the user to ensure only int imputs
card = get_int("Card: ")
# convert the card into a string so it may be indexed to manipulate individual digits
card = str(card)
# check len to make sure its the correct amount of numbers that would be in a major credit card.
if len(card) < 13 or len(card) > 16:
print("invalid len")
exit(1)
# iterate over every other number in the card starting with the second to last digit
for i in range(len(card)-2, 0, -2):
doubled = (int(card[i]) *2)
#add the string values together
sum1 = sum(int(doubled))
print(sum1)
main()
终端显示:
Traceback (most recent call last):
File "/home/ubuntu/pset6/credit/credit.py", line 22, in <module>
main()
File "/home/ubuntu/pset6/credit/credit.py", line 20, in main
sum1 = sum(int(doubled))
TypeError: 'int' object is not iterable
sum()
函数需要一个迭代器,而您给它一个 integer
。也许你正在尝试使用 sum1 += int(doubled)
.