Change the flow of code dynamically in Python

53 views Asked by At

So im writing this calculator program, and at the end of it I want to give the user an option to run it again or close the program.

I thought there was a "goto" function, but apparenty that doesnt exist.

what I tried:

if operator == "+":
    answer = number1 + number2
    print("") #line break
    print(f"the answer is {answer}")
    
redoq=input(print("would you like to redo? (y/n):"))
if redoq == "y" or "Y":
    goto(start)

if redoq == "n" or "n":
    print("Okay! This window will now close.")
    time.sleep(5)

what happened:

> "goto" is not defined
2

There are 2 answers

0
d.b On

GOTO is not considered good practice these days - see here. Python does not have an inbuilt goto. For your purpose, you could have another helper function that calls the main function recursively until you want to exit. See example below:

def foo():
    print("foo ran")
    
def call_foo():
    foo()
    
    check = input("Repeat?")
    if check == "y":
        call_foo()
    else:
        print("exiting...")
        return
0
Ruben Sutton On

Use this and make the file run itself, this should make it work.

exec(open('calculatorprogram.py').read())

You could also make it a function:

def calculatorprog():
##main program goes here
    repeat = input("Redo? y/n ")
    if repeat in "y", "Y":
        calculatorprog()
    else:
        break