Reputation: 423
I am getting 'none' as my output rather than the reversed string. I am not sure if I am printing the wrong thing. I am relatively new to loops, so bear with me, but the basic goal is to reverse 'old_string'
old_string=("I am testing") #Defining old_string
def reverse(old_string):
rng=range((len(old_string))-1,11,1) #rng= the range of the number of index values in old_string, starting with max-1 ending at 0 by steps of -1
new_string='' #New string equals the following loop
for index in rng: #For index in the above range
new_string=new_string,old_string[index] #New string equals itself PLUS the origninal old string using index values of 'index'
return new_string
print reverse(old_string)
Upvotes: 0
Views: 58
Reputation: 423
My return statement was inside the for loop, thus ending the loop. So, I moved it out of the loop, so now it is done when the loop is completely finished. (Also I fixed the range numbers)
Upvotes: 0
Reputation: 11
By placing the return statement in the for loop you are exiting the function before the for loop has finished. You need to put the return statement outside of the for loop.
Also if you just want to reverse the string you can do the following
>>> 'hello world'[::-1]
'dlrow olleh'
Upvotes: 1
Reputation: 8291
These are the errors in your version:
def reverse(old_string):
rng=range((len(old_string))-1,-1,-1) # this is the correct range that you want
new_string=''
for index in rng:
new_string += old_string[index] # concatenate strings with + (or +=)
return new_string # return outside of your loop
By the way, you can always just reverse a string s
with
s[::-1]
Upvotes: 1