Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

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

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

  if __name__ == '__main__':
      while 1 == 1:
          main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

def main():
    txt1 = input("Please enter value only 2 
")
    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 
")
        if txt1 == 2:
            print txt
            print txt1
            time.sleep(3)

The latter avoids issues with recursion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...