循环退出一段时间后如何继续 python 程序



我有一个python3程序,它根据用户的输入猜测一个人的姓氏。但是我想出了如果用户现在回答如何中断,但是当用户说是时,它只是使用相同的初始问题再次重新进入循环。

while True:
    answer = input('Do you want me to guess your name? yes/no :')
    if answer.lower() == 'no':
        print("Great")
    else:
        time.sleep(2)
        exit('Shame, thank you for playing')
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)

演示 - 如果用户回答"是"

Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :

等。

所以基本上我希望程序在"否"上退出,但继续下一个问题,即"请告诉我你姓氏的第一个字母?

知道吗?

我在这里提出了一些建议,我可以使用 while 循环,但就问题而言,我没有做对。

请以不那么技术性的方式回答,因为我对python的了解非常有限,仍在努力学习。

起初我误解了这个问题。当用户说"是"时,您实际上需要中断while循环,以便您可以继续第二个问题。当他说"不"时,使用exit是可以的,只要记住它会退出整个程序,所以如果你想在他说不之后做其他事情,最好使用return并将它们放入函数中。

你的代码应该或多或少是这样的:

import time
while True:
    answer = input('Do you want me to guess your name? yes/no :')
    if answer.lower() == 'yes':
        print("Great")
        break    # This will break the actual loop, so it can pass to next one.
    elif answer.lower() == 'no':
        # I recommend printing before so if it's running on a terminal
        # it doesn't close instantly.
        print('Shame, thank you for playing')
        time.sleep(2)
        exit()
    # I suggest adding this else because users don't always write what we ask :P
    else:
        print('ERROR: Please insert a valid command.')
        pass    # this will make it loop again, until he gives a valid answer.
while True:
    # code of your next question :P repeat proccess.

请随时询问有关代码的任何问题:)

正如CoryKramer在评论中指出的那样,使用中断而不是退出。Exit 是一个 python 函数,它退出整个进程,从而关闭解释器本身。

中断将关闭它所属的最接近的循环。因此,如果你有两个 while 循环,一个写在另一个循环中。中断只会关闭内部 while 循环。

一般来说,你的代码会像这样

while True:
    answer = input('Do you want me to guess your name? yes/no :')
    if answer.lower() == 'yes':
        print("Great")
        lastname = input('Please tell me the first letter in your surname?').lower()
        time.sleep(2)
    else:
        time.sleep(2)
        print("Thank you for playing!")
        break

只要用户继续输入 yes,这将不断循环。

如果你想一个无限的while循环,你需要控制你的循环状态。我还创建了一个姓氏。对于大型项目,使用单独的函数更具可读性。

def SurnameFunc():
  return "Test Surname ..."
State= 0
lastname_tip = ""
while(True):
  if(State== 0):
    answer = input('Do you want me to guess your name? yes/no :')
    if(answer == 'no') :
      print ("You pressed No ! - Terminating Program ...")
      break
    else:
      State = 1
  elif(State == 1):
    lastname_tip = input('Please tell me the first letter in your surname?').lower()
    State = 2
  elif(State == 2):
    print ("Your Surname is ..." + SurnameFunc())
    State = 0

print ("Program Terminated !")

最新更新