thornbird thornbird - 1 month ago 14
Python Question

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.

Answer

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.