【发布时间】:2022-11-05 08:51:32
【问题描述】:
我对 Python 很陌生,感谢理解
编写一个函数来确定前 n 个素数。 n 的值取自用户输入。 该程序应该打印所有请求的素数。
完成此任务后,程序应再次询问用户是否要打印另一组 质数。如果是,程序应该重做任务。否则,它应该终止程序。
使用迭代/循环来解决这个问题。
例子:
Enter the value of n: 5
The first 5 prime numbers are...
2
3
5
7
11
--End--
Would you like to go again? (Yes/No): Yes
Enter the value of n: 3
The first 3 prime numbers are...
2
3
5
--End--
Would you like to go again? (Yes/No): No
Closing program...
我对 Python 很陌生,感谢理解
这是我的代码:
def prime_list():
n = int(input("Enter the value of n: "))
print("The first", n, "prime numbers are...")
var = 0
num = 2
while True:
prime = True
for i in range (2, num//2 +1):
if num%i == 0:
prime = False
break
if prime == True:
print(num)
var += 1
if var == n:
break
num += 1
print("==END==")
def redo():
text = str(input("Would you like to go again? (Y/N): "))
if text == str("N"):
print("Terminating Program...")
quit()
if text == str("Y"):
prime_list()
prime_list()
redo()
为什么我的代码只运行两次?执行时它只运行两次。如何,为什么?
【问题讨论】:
-
它运行两次,因为您只调用了两次该函数:调用 prime_list 和调用 redo 时。将重做代码放在一个循环中,并让 N 选项打破循环而不是调用
quit -
您可能打算进行相互递归,其中
prime_list调用redo。 -
或者您可以将调用
prime_list和redo置于无限循环while True:中。我必须说,相互递归对我来说看起来非常优雅,另一方面,递归在这里并不是真正必要的,因此可能有点矫枉过正。
标签: python