Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无限循环开始了,为什么?_Python_Compiler Errors - Fatal编程技术网

Python 无限循环开始了,为什么?

Python 无限循环开始了,为什么?,python,compiler-errors,Python,Compiler Errors,我使用下面的代码在Python中查找数字之和,但在运行程序时开始无限循环 def digit_sum(n): k=str(n) i=0 while i<range(len(k)): l=int(i) j=0 j=j+i print j i+=1 digit_sum(1234) def位和(n): k=str(n) i=0 而我压痕是错误的。while循环不在您的函数范围内。缩进它以保

我使用下面的代码在Python中查找数字之和,但在运行程序时开始无限循环

def digit_sum(n):
    k=str(n)
    i=0
    while i<range(len(k)):
        l=int(i)
        j=0
        j=j+i
        print j
        i+=1

digit_sum(1234)
def位和(n):
k=str(n)
i=0

而我压痕是错误的。while循环不在您的函数范围内。缩进它以保持在函数内部。同时为变量指定更有意义的名称。

您有缩进错误

因此,要获得正确的输出,请尝试以下方法。您可以检查此代码

def位和(n):
k=str(n)
i=0
j=0
而i
看起来您是python新手,所以我将帮助您解决问题。我看过您的代码。您似乎有缩进问题和一些逻辑问题,所以我更新了它。请看这里

def digit_sum(n):
  k = str(n)
  j = 0 #sum for digits
  i  = 0
  while i in range(len(k)):
    #Add convert string to the int and add to the sum
    j = j + int(k[i]);
    #increment Counter
    i = i+1
    print j # print Sum
digit_sum(1234)

有关缩进的更多信息,您可以

将代码和错误消息以文本形式发布。看起来您有缩进错误。isum(int(ch)for ch in str(n))
@MohitMalik range函数返回一个序列,因此当调用它时,它将返回从0到len(k)的序列如果您熟悉java,那么在中使用哪个iterable?每个函数都是这样的,您也可以使用,而我def digit_sum(n): k = str(n) j = 0 #sum for digits i = 0 while i in range(len(k)): #Add convert string to the int and add to the sum j = j + int(k[i]); #increment Counter i = i+1 print j # print Sum digit_sum(1234)