Reputation: 303
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?
Upvotes: 1
Views: 510
Reputation: 2359
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.
Upvotes: 0
Reputation: 239623
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
Don't use str
as a variable name, it hides the builtin str
function.
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
Upvotes: 7