moy luna
moy luna

Reputation: 11

How would I go about creating an input input that restarts the code from the users end?

I am looking for a way to include an input at the end of this code where the user will be prompted with a choice to restart the code or end the code without having to manually restart it.

def correct_result(choice,num):
if choice.lower() == 'square':      #Prints the Square of a number Ex. 2^2 = 4
    return num**2

elif choice.lower() == 'sqrt':      #Prints the Square root of a number Ex. √4 = 2 
    return num**.5

elif choice.lower() == 'reverse':   #Changes the sign of the number
    return(-num)

else:
    return 'Invalid Choice'         #prints an error message

choice = input()                  #Creates a answer box to enter the desired choice
num = int(input())                #Creates a second box that lets the user enter their number
print(correct_result(choice,num)) #Prints either the desired choice or the error function

Upvotes: 1

Views: 49

Answers (1)

Alexander L. Hayes
Alexander L. Hayes

Reputation: 4273

Wrap your choice and num input in a while loop, break when the user chooses "exit":

def correct_result(choice,num):
    if choice.lower() == 'square':      #Prints the Square of a number Ex. 2^2 = 4
        return num**2
    elif choice.lower() == 'sqrt':      #Prints the Square root of a number Ex. √4 = 2
        return num**.5
    elif choice.lower() == 'reverse':   #Changes the sign of the number
        return(-num)
    else:
        return 'Invalid Choice'         #prints an error message

while True:

    choice = input("Choice: ")                  #Creates a answer box to enter the desired choice

    if choice == "exit":
        exit()

    num = int(input("Number: "))                #Creates a second box that lets the user enter their number
    print(correct_result(choice,num)) #Prints either the desired choice or the error function

Upvotes: 1

Related Questions