我在嘗試使用 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")
強文本
uj5u.com熱心網友回復:
首先你應該洗掉
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362956.html
上一篇:C vector列印出奇怪的元素
