【问题标题】:I'm having issues using generators with the input function in python 3我在 python 3 中使用带有输入函数的生成器时遇到问题
【发布时间】:2020-09-17 08:24:03
【问题描述】:
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 函数与输入函数一起工作。如果我尝试使用输入函数调用每个产生的值,我什么也得不到,但是如果我在不使用输入的情况下调用该函数,我会取回我的值。是不是生成器不能和输入函数一起工作?

【问题讨论】:

  • 你的缩进关闭了,你能看一下吗?
  • 你试过学习测试驱动开发吗?

标签: python generator primes yield


【解决方案1】:

你犯的错误是忘记了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()

【讨论】:

  • 哦,是的,我做到了。谢谢钢铁侠
猜你喜欢
  • 2020-12-02
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 2018-10-15
相关资源
最近更新 更多