thornbird
thornbird

Reputation: 45

Trying to learn how loops work, what is going wrong?

The question is :

Given a string, return a string where for every char in the original, there are two chars.

This is my attempt:

def double_char(str):
    n = 0
    for x in range(0, len(str)):
        return 2*str[n]
        n = n+1

When I run it, it only returns 2 versions of the first letter and doesn't loop properly. So for double_char(Hello) it just returns HH.

What is going wrong? Thanks in advance for any help, sorry for the really beginner question.

Upvotes: 3

Views: 165

Answers (4)

Hussein Ibrahim
Hussein Ibrahim

Reputation: 21

def double_char(str):

    string = ''
    for i in range(len(str)):
      string += str[i] * 2
      i += 1

    return string

Upvotes: 0

Habib Koç
Habib Koç

Reputation: 11

Here is a different way to solving the question.

def double_char(str):
  new_str = ""
  for i in range(len(str)):
    new_str += (str[i]*2)
  return new_str

double_char('Hello')
'HHeelllloo'  

Upvotes: 1

Paul Rooney
Paul Rooney

Reputation: 21609

The return is causing your function to return in the first iteration so it just returns 2 of the first letter.

What you may have intended to write was something like

def double_char(s):
    n = 0
    r = ''
    for x in range(0, len(s)):
        r += 2*s[n]
        n = n+1

    return r

Building a string incrementally that is just 2 of each character.

A neater refactor of that function (without duplicating the other answer by using a comprehension) is

def double_char(s):

    r = ''
    for c in s:
        r += 2*c

    return r

You also should not use str as a variable name. It is a built in type and you are hiding that by defining a variable called str.

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78536

return returns control to the caller once reached, thus exiting your for loop prematurely.

Here's a simpler way to do that with str.join:

def double_char(s):
    return ''.join(i*2 for i in s)

>>> s = 'Hello'
>>> double_char(s)
'HHeelllloo'

Do not use str as name to avoid shadowing the builtin str function.

Upvotes: 1

Related Questions