Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么';这不是环路吗?_Python_Loops_While Loop - Fatal编程技术网

Python 为什么';这不是环路吗?

Python 为什么';这不是环路吗?,python,loops,while-loop,Python,Loops,While Loop,为什么这个代码不循环返回产品字符串中的每个字符?它只返回第一个并停止 def fix_machine(debris, product): n = 0 while debris.find(product[n]) != -1: return product[n] n = n + 1 对于noob问题很抱歉当您使用return时,函数将立即终止并返回返回值。如果要从函数返回多个值,可以使用yield。还要注意,您应该检查n是否仍在产品的范围内 def

为什么这个代码不循环返回产品字符串中的每个字符?它只返回第一个并停止

def fix_machine(debris, product):
    n = 0
    while debris.find(product[n]) != -1:
        return product[n]
        n = n + 1

对于noob问题很抱歉

当您使用
return
时,函数将立即终止并返回返回值。如果要从函数返回多个值,可以使用
yield
。还要注意,您应该检查
n
是否仍在
产品的范围内

def fix_machine(debris, product):
    n = 0
    while n < len(product) and debris.find(product[n]) != -1:
        yield product[n]
        n = n + 1
输出将是例如
['s'、'o'、'm'、'e'、'']


如您所述,如果您想“在碎片中找到产品的所有字符时打印产品”,您可以尝试以下方法:

def fix_machine(debris, product):
    if all(c in debris for c in product):
        print(product)

我不确定python中的语法,但我熟悉的语言中的
return
通常会将块返回到方法调用块

您想要的是:

method
    while true
        build array
    end while
    return array
end method

这是意料之中的<代码>返回
将停止函数的执行。如果需要,您可以打印它:

def fix_machine(debris, product):
    n = 0
    while debris.find(product[n]) != -1:
        print product[n]
        n = n + 1

return
打破了循环我不知道这是什么语言,但是
return product[n]
可能会完全退出定义的方法。它似乎是Python语言。。。它是?是的,你应该减少缩进,把n=n+1放在返回之前,把返回放在while循环之外。另外,您很可能希望返回n而不是产品[n]。谢谢各位。是的,这是Python。我想做的是让Python打印出产品的字符串,如果它的所有字符都可以在碎片中找到的话。所以基本上,只要它在碎片中找到每一个,我就希望它打印出整个字符串。谢谢,现在我得到了打印和返回之间的另一个主要区别。没问题,很乐意帮助。如果你的问题解决了,请点击灰色复选框接受答案。在我的情况下,我将如何结束?谢谢,tobias。我实际上是想让它打印产品,如果它的所有字符都能在碎片中找到的话。
def fix_machine(debris, product):
    n = 0
    while debris.find(product[n]) != -1:
        print product[n]
        n = n + 1