简体   繁体   中英

Python Exit The loop and start the whole process from start once again

I am new to Python Scripting. I have written a code in python. it works pretty fine till now. What I need to know is how can I run it multiple times, I want to start the whole script from start if the condition fails. The sample code is below. This script is saved in file called adhocTest.py so I run the script like below in python shell

while 1 ==1: execfile('adhocTest.py')

The function main() runs properly till the time txt1 == 2 which is received from the user input. Now when the input of txt1 changes to other than 2 it exits the script because I have given sys.exit() what I need to know is how can I start the the script adhocTest.py once again without exiting if the input of tx1 is not equal to 2. I tried to find the answer but somehow I am not getting the answer I want.

  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()

I think this is what you want:

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())

You are only re-calling main in your else . You could re-factor as follows:

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

Alternatively, just call main() (rather than wrapping it in a while loop) and move the loop inside. I would also pass txt explicitly rather than rely on scoping:

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

The latter avoids issues with recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM