【问题标题】:How to use a While Loop to repeat the code based on the input variable如何使用 While 循环根据输入变量重复代码
【发布时间】:2021-11-19 17:47:36
【问题描述】:

我在尝试使用 while 函数进行循环时遇到了困难。 基本上我希望代码向我显示从 0 到我在输入中写入的数字的所有素数。 然后,问一个问题我是否想再做一次(如果是,从头开始重复代码)还是不退出。 我现在如何得到它只是无限重复最后的结果。 我在 while 循环中在线找到的所有结果并没有真正解释如何重复代码的某个部分。 在这方面我根本没有受过一点教育,所以如果这是一个愚蠢的问题,请原谅我。

# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes

def start(welcome):
    print ("welcome to my calculation.")

value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)

def SieveOfEratosthenes(n):
    prime = [True for i in range(n + 1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p ** 2, n + 1, p):
                prime[i] = False
        p += 1
    prime[0] = False
    prime[1] = False
    print("Primary numbers are:")
    for p in range(n + 1):
        if prime[p]: print(p)


# driver program
if __name__ == '__main__':
    n = value
    SieveOfEratosthenes(n)

pitanje = input("do you want to continue(yes/no)?")

while pitanje == ("yes"):
    start: SieveOfEratosthenes(n)
    print("continuing")
if pitanje == ("no"):
    print("goodbye")

强文本

【问题讨论】:

    标签: loops while-loop repeat


    【解决方案1】:

    首先你应该删除

    value = input("number?:\n")
    print(f'you have chosen: {value}')
    value = int(value)
    

    从代码顶部开始,所有内容都必须在 __main__ 程序中。

    基本上,您需要做的是创建一个主 While 循环,您的程序将在其中运行,它会一直循环,直到响应不是“是”。

    对于每次迭代,您都会在开始时询问一个新数字,以及它是否必须在最后保持循环。

    类似这样的:

    # driver program
    if __name__ == '__main__':
        # starts as "yes" for first iteration
        pitanje = "yes"
    
        while pitanje == "yes":
            # asks number
            value = input("number?:\n")
            print(f'you have chosen: {value}')
            value = int(value)
    
            # show results
            start: SieveOfEratosthenes(value)
    
            # asks for restart
            pitanje = input("do you want to continue(yes/no)?")
    
        #if it's in here the response wasn't "yes"
        print("goodbye")
    

    【讨论】:

      猜你喜欢
      • 2020-02-22
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2018-03-05
      相关资源
      最近更新 更多