Python 中的索引错误(索引超出范围)

Index error in Python( index out of range)

given_number=str(input("Enter the number:"))
total=str(0)
num=0
while num<=len(given_number):
       total+=given_number[num]
       num+=1
print(total)  

明白了indexerror.Where是错吗?

您正在向输入字符串添加 "0"。你可以直接做

print("0"+input())

而是使用最冗长的方法将内容附加到字符串。

问题出在您的 while 循环中。显然,您的循环遍历 0 到输入字符串的长度,而 0 base list/array/string 的最大索引是

len(given_number)-1

像这样修改你的代码。

   given_number=str(input("Enter the number:"))
   total=str(0)
   num=0
   while num<len(given_number): # Note: I use < not <=
       total+=given_number[num]
       num+=1
   print(total)  

希望对您有所帮助。