Search code examples
pythonwhile-loopprogram-entry-pointrepeat

How to repeat program after running the whole program in Python?


I wrote a short program comparing two integers and providing an appropriate answer at the end. I want the program to repeat itself in case integer was not written in 'userint'.

Core program:

from random import randint
rn = randint(0,5)
print("The randomly generated integer is:",rn)
userint= input("Enter an integer:")

try:
    if userint == rn:
        print("Numbers are equal!")
    elif userint > rn:
        print(userint)
    else:
        print(rn)
except:
    print("You have not entered an integer!")

if input("Do you want to repeat(y/n)").lower()== "  N":
    break

Here is what I have tried using:

while True:
    from random import randint
    rn = randint(0,5)
    print("The randomly generated integer is:",rn)
    userint= input("Enter an integer:")

    try:
        if userint == rn:
            print("Numbers are equal!")
        elif userint > rn:
            print(userint)
        else:
            print(rn)
    except:
        print("You have not entered an integer!")

    if input("Do you want to repeat(y/n)").lower()== "  N":
        break

I have also tried another method of repeating the program as:

def main():

    from random import randint
    rn = randint(0,5)
    print("The randomly generated integer is:",rn)
    userint= input("Enter an integer:")

    try:
        if userint == rn:
            print("Numbers are equal!")
        elif userint > rn:
            print(userint)
        else:
            print(rn)
    except:
        print("You have not entered an integer!")

    restart = input("Do you want to start again?").lower()
    if restart == "yes":
        main()
    else:
        exit()
main()

In both cases, program asks a user to input the value. Than, despite the value it runs the restart part of the program without conduction actual comparison of the values.

Could someone guide me on how to fix the program and allow it to compare values and if user inputs not an integer print("You have not entered an integer!"), ask "Do you want to start again?", and run the program again?


Solution

  • You can use isnumeric to check whether the input is integer or not.

    def main():
    
        from random import randint
        rn = randint(0,5)
        print("The randomly generated integer is:",rn)
        userint= input("Enter an integer:")
        if userint.isnumeric():
            userint=int(userint)
        try:
            if userint == rn:
                print("Numbers are equal!")
            elif userint > rn:
                print(userint)
            else:
                print(rn)
        except:
            print("You have not entered an integer!")
    
        restart = input("Do you want to start again?").lower()
        if restart == "yes":
            main()
        else:
            exit()
    main()