Drew Barry Jenkins
Drew Barry Jenkins

Reputation: 29

Why doesn't the loop work as it be programmed?

While I tried to execute the following code, I faced some problem in loop iterations and couldn't figure out what's the problem might be.

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

Upvotes: 0

Views: 252

Answers (3)

Innat
Innat

Reputation: 17219

Try something like:

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

print(string_splosion('Code'))

Upvotes: 0

Manos Gero
Manos Gero

Reputation: 31

if you have return inside in a loop the loop is raning only for one time.

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

Upvotes: 3

eddey
eddey

Reputation: 31

you leave the function after the first return. I think this would be the right solution

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

Upvotes: 3

Related Questions