![]() |
Not quite getting the correct Output from a function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Not quite getting the correct Output from a function (/thread-20233.html) |
Not quite getting the correct Output from a function - twinpiques - Aug-01-2019 Hello. I have a function that I'm trying to create. When receiving a non-empty string input, I want to return a string containing every other character 2n+2 times. (Where "n" is the 0-based index of the letter). Example: input_string = "Rivers" #RRvvvvvvrrrrrrrrrr def string_expansion( input_string ): n=0 if len(input_string) == 0: return "invalid entry" #for n in range(len(input_string)): # value = input_string[n::2] # return value * (2*n+2) for n in range(0,len(input_string),2): #value = input_string[n] #strlen = len(input_string) print(value * (2*n+2)) pass input_string = "Rivers" print(string_expansion(input_string))I am getting: I want to get: What am I goofing up here?
RE: Not quite getting the correct Output from a function - Yoriz - Aug-01-2019 Your code is printing the value per loop and not returning anything. You need a container for your string before the loop, add to it inside the loop and return it after the loop. RE: Not quite getting the correct Output from a function - perfringo - Aug-01-2019 If function doesn't return anything explicitly with return statement then it returns None (you can see it in your output: three lines printed and then None). In case of empty string function returns 'invalid entry' therefore there will be no None. I would go for oneliner: >>> s = 'Rivers' >>> ''.join(char*(2*(i-1)+2) for i, char in enumerate(s, start=1) if i % 2) 'RRvvvvvvrrrrrrrrrr' RE: Not quite getting the correct Output from a function - twinpiques - Aug-04-2019 Thank you for the replies. I tried both recommendations and they worked wonderfully...and I learned two different approaches in the process. Much appreciated! |