1

I'm practicing some basic coding, I'm running a simple math program running in the terminal on Visual Studio Code.

How do I create an option to return to the beginning of the program, or exit the program after getting caught in an if statement?

Example:

#beginning of program

user_input=input('Please select "this" or "that": ')
findings=user_input

If findings == this:
        print(this)
        # How can I redirect back to first user input question, instead 
        # of just ending here? 
if findings == that:
        print (that)
        # Again, How do I redirect back to first user input, instead of 
        # the program ending here?  
# Can I setup a Play_again here with options to return to user_input, 
        # or exit program? And then have all other If statements 
        # redirect here after completion? How would I do that? with 
        # another If? or with a for loop? 
#end program
py_Rooky
  • 11
  • 1
  • 7
  • that format is not how i typed that at all! I wrote the example like code! why did it removes spacing, indents and return lines? – py_Rooky Jan 30 '22 at 06:43
  • accept my edit when you want code segments in stack overflow start with ``` and end ``` – carlosdafield Jan 30 '22 at 06:48
  • 1
    @py_Rooky, are you sure that the code is complete? What is `z` and what is `check(condition)`? Do you mean you pass checks there? Though I'm bad at `while` loops, [here](https://stackoverflow.com/a/67726954/16136190) is something I guess you want. You can `def`ine functions where you want to skip to and call them in other parts of your code (from where you want to go). – The Amateur Coder Jan 30 '22 at 07:05
  • 1
    @TheAmateurCoder I edited the question to make it cleaner and be more direct with my question, now that I understand what I'm trying to do better. The direct question is, "How do I create an option to go back to the beginning of the program, or clean exit, when I get caught in an if statement?" – py_Rooky Jan 30 '22 at 14:58
  • 1
    @py_Rooky, where is the beginning of the program in "How do I return to beginning of program?"? – The Amateur Coder Jan 30 '22 at 15:15
  • @TheAmateurCoder that matters? Ok.. I think i have a better example.. I will edit one more time for a cleaner example. – py_Rooky Jan 30 '22 at 15:24
  • 1
    @TheAmateurCoder OK... I think I got a much more clear and easy to understand example this time. Hopefully I can get answers now instead of more questions that don't seem relevant to my question. LOL... Not criticizing you, I'm criticizing me. – py_Rooky Jan 30 '22 at 15:39
  • 1
    @py_Rooky LOL, nice. I was seeing how to use another technique to get it done. I'll post an answer that uses the technique soon. If I take too long, [here's the technique](https://stackoverflow.com/a/21949524/16136190). – The Amateur Coder Jan 30 '22 at 15:45
  • 1
    @py_Rooky, please check [my answer](https://stackoverflow.com/a/70916684/16136190) and let me know if it works. I've replaced `print(float_condition)` with `play()`. Note that using `play(just_define=True)` instead of `play()` will not execute it. – The Amateur Coder Jan 30 '22 at 16:55

3 Answers3

2

You can try wrapping the whole program in a while loop like this:

while(True):
    user_input=input('Please select "this" or "that": ')
    this = 'foo'
    if user_input == this:
        print(this)
        continue 

    if user_input == this:
        print(this)
        continue    
Hack3r
  • 79
  • 6
  • 1
    12 HOURS of research, googling, reading python instructions and the way to keep from getting locked in an if statement is "continue"?? My code is in a while loop. I was just trying to simplify the example. – py_Rooky Jan 30 '22 at 15:56
  • so did it fix the problem? – Hack3r Jan 30 '22 at 15:57
  • What about redirecting to a specific part of program like If == true: print(true) #now go to play_again. ?? – py_Rooky Jan 30 '22 at 16:00
  • you can try wrapping the blocks of code in an if statement and creating a variable to keep track which if statement to run like `nextcode = 'first if statement'` and check if nextcode is equal to 'first if statement' in the while loop – Hack3r Jan 30 '22 at 16:04
  • Nope. "continue" doesn't work. just locks it up. doesn't even close out. just stops running. – py_Rooky Jan 30 '22 at 16:16
  • i updated the answer try running the code – Hack3r Jan 30 '22 at 16:25
  • That works! I will try and implement it into my code! I'll let you know how it works out! Thanks! – py_Rooky Jan 30 '22 at 16:31
  • It worked! I was finally able to add a "would you like to play again" command and loop back to the beginning of the program! Thank you very much! BUT.. it resulted in a new issue. Now my "print(result)" inside of the 'if' statements are printing 5 times instead of once... wonder if I have the Play_again in the wrong place? hmm... I might post a new question using the exact code I'm working with. – py_Rooky Jan 30 '22 at 16:54
  • does it actually print 5 times on each iteration or each time you answer? if it's each time you answer consider using the `os` module and running the following `os.system('cls' if os.name in ('nt', 'dos') else 'clear')` each time before you call `continue`. – Hack3r Jan 30 '22 at 16:59
0

Unfortunately, that 'another technique' I thought of using didn't work.

Here's the code (the first example modified):

import sys

def main():
    # Lots of setup code here.
    def start_over():
        return #Do nothing and continue from the next line
    condition = 1==1 #Just a sample condition, replace it with "check(condition)".
    float_condition = condition

    def play(*just_define:bool):
        if not just_define:
            play_again = input('play again? "y" or "n"')
    
            if play_again == 'y':
                start_over() #Jump to the beginning of the prohram.
            if play_again == 'n':
                sys.exit() #Exit the program
        
    while True:
        if float_condition == True:
            # print(float_condition)
            play() #skip to play_again from here?
    
        if float_condition == False:
            #print(float_condition)
            play() #skip to play_again from here?

    #I removed the extra "main()" which was here because it'd cause an infinite loop-like error.

main()

Output:

play again? "y" or "n"y
play again? "y" or "n"n

Process finished with exit code 0

The * in the play(*just_define:bool) function makes the just_define parameter optional. Use the parameter if you want to only tell Python to search for this function, so it doesn't throw a ReferenceError and not execute anything that's after the line if not just_define:. How to call like so: play(just_define=True).

I've used nested functions. I've defined play so that you can call it from other places in your code.

The Amateur Coder
  • 789
  • 3
  • 11
  • 33
-1

Thanks to @Hack3r - I was finally able to choose to return back to the beginning of the program or exit out. But it resulted in a new issue. Now my print(results) are printing 4 or 5 times...

Here is the actual code I built and am working with:

def main():

    math_Options=['Addition +','Subtraction -','Multiplication *','Division /']
    math_func=['+','-','*','/']
    for options in math_Options:
        print(options)
    print('Lets do some Math! What math function would you like to use? ')
   
    while True:
        my_Math_Function = input('Please make your choice from list above using the function symbol: ') 
        my_Number1=input('Please select your first number: ')
        x=float(my_Number1)
        print('Your 1st # is: ', x)
        my_Number2=input('Please select your Second Number: ')
        y=float(my_Number2)
        print('Your 2nd # is: ', y)
        z=float()
        print('')
        for Math_function in math_func:
            if my_Math_Function == math_func[0]:
                z=x+y
            if my_Math_Function == math_func[1]:
                z=x-y
            if my_Math_Function == math_func[2]:
                z=x*y
            if my_Math_Function == math_func[3]:
                z=x/y

            if (z % 2) == 0 and z>0:    
                print(z, ' Is an EVEN POSITIVE Number')
            if (z % 2) == 1 and z>0:    
                print(z, ' IS a ODD POSTIVE Number')
            if (z % 2) == 0 and z<0:
                print(z, ' Is an EVEN NEGATIVE Number')
            if (z % 2) ==1 and z<0:
                print(z, ' IS a ODD NEGATIVE Number')
            if z==0:
                print(z, 'Is is Equal to Zero')
            print('')
        play_again=input('Would you like to play again? "y" or "n" ')
        if play_again == 'y':
            continue
        if play_again == 'n':
            break
        main()
main()
The Amateur Coder
  • 789
  • 3
  • 11
  • 33
py_Rooky
  • 11
  • 1
  • 7
  • can someone edit that for me so it looks right? thanks. Still learning! – py_Rooky Jan 30 '22 at 17:08
  • I'll try to edit it later because the 'Suggested edit queue is full`... See [how to format posts](https://stackoverflow.com/editing-help) using 3 backticks (not inverted commas). BTW, does the code in [my answer](https://stackoverflow.com/a/70916684/16136190) work? – The Amateur Coder Jan 30 '22 at 17:26
  • 1
    @TheAmateurCoder I haven't had a chance to implement your code structure yet. I'm very curious to try it out! Thank you for posting it! I'll let you know how it works out as soon as I get a chance to try it out! – py_Rooky Jan 31 '22 at 03:59