[英]Loop from the start of the code until the user says stop in Python
這是我在學校的老師給我們的問題:
編寫 Python 程序以接受 integer N 的值並顯示 N 的所有因數。使用用戶控制的循環對多個整數重復上述操作。
我對代碼的主要部分沒有任何問題,但是我不明白如何正確循環它,以便代碼再次從頭開始運行,直到用戶在提示時最后說 N。
這是我的代碼:
#this is the main part of the code
def print_factors(x):
print("The factors of",x,"are: ")
for i in range(1,x+1):
if x%i==0:
print(i)
#this is the error handling part of the code
while True:
try:
n=int(input("Please enter a number: "))
except ValueError:
print("Please enter a valid number.")
continue
else:
break
print_factors(n)
#this is the looping part where i am having trouble
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
while N not in 'YN':
if N == 'Y':
print_factors(int(input("Enter a number: ")))
elif N == 'N':
break
else:
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
print_factors(int(input("Enter a number: ")))
我想把 go 的代碼回到開始並再次要求輸入,然后詢問用戶是否要繼續等等。 但是當我走到最后時,循環顯示了這些結果:
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 42
The factors of 42 are:
1
2
3
6
7
14
21
42
如果我輸入 y 以外的其他內容,那么它也可以工作,並且僅在循環一次后結束。 我希望它無限循環,直到用戶給出命令以“y”或“Y”輸入停止並在所有其他情況下顯示錯誤消息。
我通過將您的內部while
循環移動到else
案例來解決您的問題。 此外,在if
語句N == 'Y'
中,我再插入一個N = input(...)
命令:
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
if N == 'Y':
print_factors(int(input("Enter a number: ")))
N = input("Do you want to continue to find factors Y/N: ").upper()
elif N == 'N':
break
else:
while N not in 'YN':
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
結果:
Please enter a number: 15
The factors of 15 are:
1
3
5
15
Do you want to continue to find factors Y/N: y
Enter a number: 23
The factors of 23 are:
1
23
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 32
The factors of 32 are:
1
2
4
8
16
32
Do you want to continue to find factors Y/N: n
>>>
try-catch
塊包含到用戶控制的while
循環中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.