[英]Continuing a while loop after breaking a nested for loop
在嵌套嵌套循環中滿足某些條件之后,我正在尋找一種更pythonic的方式來繼續while循環。 對我有用的非常笨拙的代碼是:
tens = ['30','40','50','60','70','80','90','00']
z=0
while z==0:
num = input('Please enter a number: ')
z=1
for x in tens:
if num[0]=='0' or x in num:
print('That was an invalid selection, please try again.\n')
z=0 # There has GOT to be a better way to do this!
break
print(num+' works, Thank You!')
我可以使用try / except來回答這個問題 :
tens = ['30','40','50','60','70','80','90','00']
while True:
num = input('Please enter a number: ')
try:
for x in tens:
if num[0]=='0' or x in num:
print('That was an invalid selection, please try again.\n')
raise StopIteration
except:
continue
break
print(num+' works, Thank You!')
我面臨的挑戰是
a)在滿足if的情況下繼續while循環(請求新輸入)(換句話說,中斷for循環並在同一步驟中繼續while循環)
b)在測試每個新輸入時,從頭開始運行可迭代的十位。
注意:此問題與Reddit Challenge#246 字母拆分有關
更新:合並了HåkenLid提供的答案,代碼變為
tens = ['30','40','50','60','70','80','90','00']
while True:
num = input('Please enter a number: ')
if num[0]=='0' or any(t in num for t in tens):
print('That was an invalid selection, please try again.\n')
continue
break
print(num+' works, Thank You!')
我還沒有解決“從嵌套的for循環中中斷/繼續”的問題,但是用any()函數代替循環肯定對我有用。
不需要您的for
循環。 只需in
關鍵字中使用。 但是除此之外,您可以使用break
很好。
tens = ['30','40','50','60','70','80','90','00']
while True:
num = input('Please enter a number: ')
if num in tens:
break
print('That was invalid selection, please try again.\n')
print(num+' works, Thank You!')
在大多數情況下,具有嵌套循環是不好的設計。
您的功能應始終盡可能小。 遵循該規則,您將永遠不會違反SOLID(單一負責原則)的第一條規則。
您的代碼可能如下所示:
tens = ['30','40','50','60','70','80','90','00']
def main():
while 1:
num = input('Please enter a number: ')
if nested_test(num):
print('That was an invalid selection, please try again.\n')
break
def nested_test(num):
for x in tens:
if <some test>:
return True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.