1

Given this code:

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

Is result = "" the initialization of a string? If so, was it necessary to do in the first place?

1
  • 1
    Note that this whole thing is rather inefficient; it's better to join a list than to build a string a character at a time since with immutable strings this means creating a new string object every iteration. Commented Jan 23, 2014 at 4:59

2 Answers 2

7

When you do

result += ...

it basically means that

result = result + ...

Python will not know the value result at this point. So, it will throw this error

UnboundLocalError: local variable 'result' referenced before assignment

Anyway, it is always better to initialize the variables.

Suggestions

  1. Don't use str as a variable name, it hides the builtin str function.

  2. What you are trying to do, can be done in a single line, like this

    return "".join(i*2 for i in input_string)
    

def double_char(input_string):
  return "".join(i*2 for i in input_string)

print double_char("thefourtheye")           # tthheeffoouurrtthheeyyee
Sign up to request clarification or add additional context in comments.

Comments

0

While Python doesn't require you to state the type of a variable before using it (e.g. int a = 10 instead of just a = 10), it is necessary for the variable result to exist before += can be used with it. Otherwise when you use result += ... Python will try result = result + ....

As another suggestion, avoid naming a variable str since it overwrites the built-in str function/type in Python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.