Bacodee
Bacodee

Reputation: 1

'Returning' if statement if user says 'no'

I'm still quite new to python so I've decided to create a program that asks the user what application they want to open if they type it in.

If the user types in anything else that's not an application in the prompts code, I want to have the question to 'reset' or 'return' to it's original state so I don't have to keep opening up a new terminal tab to achieve this but I don't know how!

Here's some code just to get an idea:

import os
import subprocess

print ('What do you want to open?')

prompt = raw_input('> ')

if prompt == 'safari':
    print('Opening Safari...')
    subprocess.call(
    ["/usr/bin/open", "-W", "-n", "-a", "/Applications/Safari.app"]
    )
else:
    print ('No Applications have been selected!')
    #Return to the original question#

Upvotes: 0

Views: 97

Answers (1)

Corentin Pane
Corentin Pane

Reputation: 4943

What about a while True that will loop forever?

import os
import subprocess

while True:
    print ('What do you want to open?')

    prompt = raw_input('> ')

    if prompt == 'safari':
        print('Opening Safari...')
        subprocess.call(["/usr/bin/open", "-W", "-n", "-a", "/Applications/Safari.app"])
    elif prompt == 'quit':
        break # will break out of the while loop and exit the program
    else:
        print ('No Applications have been selected!')
        #Return to the original question#

As @FedericoS suggests, use the break statement to break out of the loop when you need.

Note that your program can still crash if exceptions occur. To make sure it doesn't, have a look at exception handling in Python.

Also note that due to the blocking aspect of subprocess.call, the script will only loop back when the launched process exits. Consider using subprocess.Popen instead if you wish to immediately loop back.

Upvotes: 1

Related Questions