Ad

Write A Function That Takes A String As An Argument And Displays The Letters, One Per Line Using Loops In Python

I'm learning to program and I'm using "how to think like an computer scientist" the above question is an exercise This is the program without a function

fruit = "banana"

index = 0

while index < len(fruit):

letter = fruit[index]
print(letter)
index = index + 1

I want to put that into a function like

def tranversal(fruit):
    index = 0

    while index < len(fruit):

        letter = fruit[index]
        return letter
        index += 1

        print(tranversal("apple"))

However this is only printing the first letter of "apple" and if I use print statement instead of return I will get None. I'm very confused and need help !!

Ad

Answer

Seems like you didn't understand the purpose of the return statement inside a function. You might want to read this answer first to make things clear.

Once you understand the difference between print() and return, you should define what your function needs to do. Does it need to return the answer or is printing it on the screen enough?

Assuming the latter, given that strings are iterable, a more pythonic way to do it would be:

def transversal(fruit):
    for letter in fruit:
        print(letter)

Note that since the function is not explicitly returning a value if you try something like:

foo = transversal("banana")

the variable foo will hold the value None.

If you want your function to return the answer and not print it, you could append each letter to an empty result string, with separators for each new line and after you are done with that, simply return result. It could be a good exercise, so you should give it a try :).

Ad
source: stackoverflow.com
Ad