how to return values made in a for loop

so I have this code:

import random as r
def reverse(string):
    stri = list()
    for i in range(len(string)):
        stri.insert(0, string[i])
    for j in range(len(stri)):
        print(stri[j], end="") 

and I want to return the values instead of printing them.
how do I make it to where the function returns the values and doesnt print them?

Upvotes: 2

Views: 58

Answers (1)

Mark
Mark

Reputation: 92461

You can just return instead of looping through and printing:

def reverse(string):
    stri = list()
    for i in range(len(string)):
        stri.insert(0, string[i])
    return stri

If you use it like:

reverse("hello")

You'll get the array back: ['o', 'l', 'l', 'e', 'h']

If you want a string instead you can return the joined string:

def reverse(string):
    stri = list()
    for i in range(len(string)):
        stri.insert(0, string[i]) 
    return "".join(stri)

Then the function will return 'olleh'.

If you want to use a little more of what python offers you can also do something like:

def reverse(string):
    return string[::-1]

print(reverse("hello"))
# --> olleh

Upvotes: 4

Related Questions