简体   繁体   中英

Return “none” when defining a function with a for loop

So I'm trying to create a function using for loops and splicing that prints out a word like this:

w
wo
wor
word
word
wor
wo
w

I am trying to learn about defining functions, so I want to use a function that allows both forward and reverse directions can be input. If I use the "return" function, my code terminates early. If I don't use the return function I get a "none". How can I get rid of the none?

Thanks

word = raw_input('Enter word to be spelled: ')
wordlength = len(word)
def direction(x):
    """Type direction of word to be spelled as str, forward or reverse."""

    if x == 'reverse':
        for x in range(wordlength, 0, -1):
            print word[:x]

    if x == 'forward':
        for x in range(0, wordlength + 1):
            print word[:x]           


print direction('forward')
print direction('reverse')

Just do direction('forward') instead of print direction('forward') . direction already takes care of the print ing itself. Trying to do print direction('forward') will just execute direction('forward') (printing out w , wo , etc.) and then print out the return value of direction('forward') , which is None , as it's not returning anything and there's no reason for it to return anything.

Your direction function does not return anything, and so it defaults to None . That is why when you print the function, it returns None . You can use yield :

def direction(x):
    """Type direction of word to be spelled as str, forward or reverse."""
    if x == 'reverse':
        for x in range(wordlength, 0, -1):
            yield word[:x]
    elif x == 'forward': # Also, I changed the "if" here to "elif" (else if)
        for x in range(0, wordlength + 1):
            yield word[:x]

Then you would run it as:

>>> for i in direction('forward'):
...     print i
... 

w
wo
wor
word

The direction function now returns a generator , which you can loop through and print the values.


Or, you can simply not use print :

>>> direction('forward')

w
wo
wor
word

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM