首页 > 解决方案 > 为什么循环在编程时不起作用?

问题描述

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

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'))

标签: python

解决方案


如果您在循环中返回内部,则循环仅运行一次。

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'))

推荐阅读