Skip to content Skip to sidebar Skip to footer

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 scri

Solution 1:

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.


Solution 2:

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

Post a Comment for "Python Exit The Loop And Start The Whole Process From Start Once Again"