为什么循环不能像编程一样工作?

时间:2018-06-15 07:58:59

标签: python

当我尝试执行以下代码时,我在循环迭代中遇到了一些问题,并且无法弄清楚问题可能是什么。

def string_splosion(s):
    """Takes a non-empty string s like "Code" and 
    returns a string like "CCoCodCode"
    """
    for i in range(len(s)):
        return s[i] * (i+1)

print(string_splosion('Code'))

3 个答案:

答案 0 :(得分:3)

在第一次返回后退出该功能。 我认为这将是正确的解决方案

def string_splosion(s):
  result = ''
  for i in range(len(s)):
      result += s[:i]
  result += s
  return result

答案 1 :(得分:3)

如果你在循环内部返回,那么循环只会进行一次。

def string_splosion(s):
    """Takes a non-empty string s like "Code" and 
     returns a string like "CCoCodCode"
    """
    a=''  ## empty String
    for i in range(len(s)):
        a += s[0:i] +s[i]  ## this is beter way  to do this "CCoCodCode"
    return a               ## out of the "for" loop

print(string_splosion('Code'))

答案 2 :(得分:0)

尝试类似:

def string_splosion(s):
    return ''.join(s[:i+1] for i in range(len(s)))

print(string_splosion('Code'))