繁体   English   中英

使用for循环定义函数时返回“ none”

[英]Return “none” when defining a function with a for loop

所以我正在尝试使用for循环和拼接创建一个函数,该函数输出如下所示的单词:

w
wo
wor
word
word
wor
wo
w

我正在尝试学习有关定义函数的信息,因此我想使用一个允许同时输入正向和反向的函数。 如果使用“返回”功能,我的代码会提前终止。 如果我不使用return函数,则会得到“无”。 我该如何摆脱无人?

谢谢

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')

只需执行direction('forward')而不是print direction('forward') direction已经照顾好了print本身。 尝试执行print direction('forward')只会执行direction('forward') (打印出wwo等),然后打印出direction('forward')的返回值,即None ,因为不返回任何东西,也没有理由让它返回任何东西。

您的direction函数不return任何内容,因此默认为None 这就是为什么当您打印函数时,它返回None 您可以使用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]

然后您将其运行为:

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

w
wo
wor
word

direction函数现在返回一个generator ,您可以循环generator并打印值。


或者,您根本不能使用print

>>> direction('forward')

w
wo
wor
word

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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