我的代码中有两个循环,我希望第二个循环继续(转到第一个)基本上重新启动程序。
words = []
while True:
new_item = input("Enter words to select from and type END when you have entered all words: ")
if new_item == "END":
break
words.append(new_item)
chosen = random.choice(words)
length = len(words)
print("Your list is", length, "items long\n" "The randomly chosen word is: ", chosen)
while True:
option = input("again? (y / n): ")
if option == "y":
continue
else:
break
如果用户按下" y"循环将继续,并再次输入答案。但是,我希望它继续第一个循环(重新启动程序)。 如果有任何解决方案或更简单的方法,请帮助。
p.s new to python
答案 0 :(得分:1)
为了简单起见,我建议丢弃第二个while循环(你好像是为了回到第一个循环而启动它),并将你的第一个循环嵌套在一个更大的,条件控制的循环中。使用默认值在“master”之外定义option
。虽然option
保留此值,但您将继续循环。
option = 'y'
while option.lower() in {'y', 'ye', 'yes'}:
words = []
while True:
new_item = input("Enter words to select from and type END when you have entered all words: ")
if new_item == "END":
break
words.append(new_item)
chosen = random.choice(words)
length = len(words)
print("Your list is", length, "items long\n" "The randomly chosen word is: ", chosen)
option = input("again? (y / n): ")
答案 1 :(得分:0)
将游戏定义为函数game()
,并在“第二个”while循环中调用它。如果用户输入“y”,则继续循环调用game()
agian,如果用户输入“n”则中断。
def game():
words = []
while True:
new_item = input("Enter words to select from and type END when you have entered all words: ")
if new_item == "END":
break
words.append(new_item)
chosen = random.choice(words)
length = len(words)
print("Your list is", length, "items long\n" "The randomly chosen word is: ", chosen)
while True:
game()
option = input("again? (y / n): ")
if option == "y":
continue
else:
break
答案 2 :(得分:-1)
嵌套循环。您正在模拟python中的do-while循环,它在语法时没有native do。以下是非常常见的。
while True:
# makes empty list for words.
words = []
# user enters n words before user enters END
while True:
new_item = input("Enter words to select from and type END when you have entered all words: ")
if new_item == "END":
# breaks out of inner loop and shows output
break
words.append(new_item)
# show output
chosen = random.choice(words)
length = len(words)
print("Your list is", length, "items long\n" "The randomly chosen word is: ", chosen)
# ask user for again
option = input("again? (y / n): ")
if option == "y":
# returns to top of outer loop, and empty words array
continue
else:
# ends outer loop
break