Python退出循环,从start再次启动整个过程

2024-03-29 07:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Python脚本。我用python编写了一段代码。到现在为止还不错。我需要知道的是,如果条件失败,我想从一开始就启动整个脚本。示例代码如下。此脚本保存在名为附件.py所以我在pythonshell中运行如下脚本

当1==1时: execfile('附件.py')

函数main()运行正常,直到从用户输入接收到txt1==2。现在,当txt1的输入变为2以外的值时,它会退出脚本,因为我已经给出了系统出口()我需要知道的是如何启动脚本附件.py如果tx1的输入不等于2,则再次不退出。我试图找到答案,但不知怎的,我没有得到我想要的答案。在

  import time
  import sys
  import os

  txt = input("please enter value \n")

  def main():
      txt1 = input("Please enter value only 2 \n")
      if txt1 == 2:
          print txt
          print txt1
          time.sleep(3)
      else:
          sys.exit()  

  if __name__ == '__main__':
      while 1 == 1:
          main()

Tags: 答案代码pyimporttxt脚本input附件
2条回答

您只在您的else中重新调用main。您可以重新考虑如下因素:

def main():
    txt1 = input("Please enter value only 2 \n")
    if txt1 == 2:
        print txt
        print txt1
        time.sleep(3)
    main()   

或者,只需调用main()(而不是将其包装在while循环中)并将循环移到内部。我也会显式传递txt,而不是依赖范围:

^{pr2}$

后者避免了递归问题。在

我想这就是你想要的:

import time
import sys
import os

def main():
    while True:
        txt = input("please enter value \n")
        txt1 = input("Please enter value only 2 \n")
        if txt1 == 2:
            print txt
            print txt1
            time.sleep(3) 

if __name__ == '__main__':
    sys.exit(main())

相关问题 更多 >