簡體   English   中英

我在使用 python 3 中輸入 function 的生成器時遇到問題

[英]I'm having issues using generators with the input function in python 3

def prime():
    n = 1000
    if n<2:
        return 0
    yield 2
    x = 3
    while x <= n:
        for i in range(3,x,2):
            if x%i==0:
                x+=2
                break
        else:
            yield x
            x+=2

#if i try to call each yielded value with an input function i don't get anything!

def next_prime():
    generator = prime()
    y = input('Find next prime? yes/no or y/n: ')
    if y[0].lower == 'y':
        print(generator.next())

next_prime()

#but if i call the function without using an input i get my values back


generator = prime()
def next_prime():
    print(next(generator))

next_prime()

如何使第一個next_prime function 與輸入 function 一起工作。 如果我嘗試用輸入 function 調用每個產生的值,我什么也得不到,但是如果我在不使用輸入的情況下調用 function,我會得到我的值。 是不是發電機不能與輸入 function 一起工作?

你犯的錯誤是你忘記了lower關鍵字的圓括號

def next_prime():
    generator = prime()
    y = input('Find next prime? yes/no or y/n: ')
    #forgot the round brackets 
    if y[0].lower() == 'y':
        print(next(generator))

next_prime()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM