Python 3.5.2 - Help w/ Script

sj77
sj77 used Ask the Experts™
on
Hello, Experts,

I have an issue with a script where I want the end-user once the app is hit to see the main menu. I have four definitions doing separate tasks (updating, querying or adding in records in a database).

I want my main screen to pop up a list of items for the end users to select. I read that a def main() function is the route to go. Tested it out and I have no luck running it.

def main():
    user_exit =  5
    while True:
            #prints statements that lead the end-user to decide what they would like to do
        print('Welcome to the ROWriter Database applet! What would you like to do?')
        print('')
        print('1) Insert a new store CIM info...')
        print('2) Update an existing store CIM info...')
        print('3) Delete an exisiting store CIM info...')
        print('4) Search for CIM')
        print('5) Exit the application...')
    
            #accepts user input and converts it to a string and stores into a variable
        user_input = int(input('Enter option:'))
        #if user input is equal to the exit variable then the application exits
        if user_input == user_exit:
            break
        elif user_input == 1:
                option_one()
        elif user_input == 2:
                option_two()
        elif user_input == 4:
                option_four()
  
if__name__ == "__main__":
    
    main()  

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
At the line 25, add space after if. The __name__ is a special-variable identifier that must be separated from the if keyword. The variable is filled with the string '__main__' when the program is launched as a script (that is, when it is not used as a module). In other words, that if allows you to use the same file with the program be used both as a script or as a module (to be imported from elsewhere).

The main in your code is actually a normal function that you call explicitly at the line 27. It can be given any name. There even is no special convention to name it main. But it is definitely understandable also to people who know other languages.
Try to change the tail of your code like this (add the print just above the last if):
print(__name__)
if __name__ == '__main__':
    main() 

Open in new window

I have named the script mymodule.py. When launched, it displays:
d:\__Python\sj77\ee29024671>py mymodule.py
__main__
Welcome to the ROWriter Database applet! What would you like to do?

1) Insert a new store CIM info...
2) Update an existing store CIM info...
3) Delete an exisiting store CIM info...
4) Search for CIM
5) Exit the application...
Enter option:

Open in new window

Notice the second line with the '__main__' string printed.

Now, create another program named script.py that just imports the mymodule and calls its function main() (here it is when wrapping the body into a function comes handy:
import mymodule

mymodule.main()

Open in new window

Notice that now the second line prints 'mymodule'.
d:\__Python\sj77\ee29024671>py script.py
mymodule
Welcome to the ROWriter Database applet! What would you like to do?

1) Insert a new store CIM info...
2) Update an existing store CIM info...
3) Delete an exisiting store CIM info...
4) Search for CIM
5) Exit the application...
Enter option:

Open in new window

In other words, that print command before the if was executed when the mymodule was imported. The block below the if was not executed because the condition does not hold. The main() was called explicitly a bit later from the script.py. This is the example that should make it clear why the if __name__ == '__main__': is often used, and why to wrap the functionality into a function.

You can try to use just body of main() (that is, remove the function definition, and the if tail, remove one indentation level). It will work the same way. But then it cannot be used as a module.

Author

Commented:
I just want it to work in line with the entire code. Do not want to script another script. Would that be best practice?
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Then main() is not necessary, and also the last if is not necessary. You can just use:
user_exit = 5
while True:
    #prints statements that lead the end-user to decide what they would like to do
    print('Welcome to the ROWriter Database applet! What would you like to do?')
    print()
    print('1) Insert a new store CIM info...')
    print('2) Update an existing store CIM info...')
    print('3) Delete an existing store CIM info...')
    print('4) Search for CIM')
    print('5) Exit the application...')

    #accepts user input and converts it to a string and stores into a variable
    user_input = int(input('Enter option:'))
    #if user input is equal to the exit variable then the application exits
    if user_input == user_exit:
        break
    elif user_input == 1:
        option_one()
    elif user_input == 2:
        option_two()
    elif user_input == 4:
        option_four()

Open in new window

Author

Commented:
Hmmm. Interesting, when I run the script, I get option1() starting off first as opposed to this part of the code. Mind you, this block is at the bottom after the definitions option_one(), option_two(), etc are defined above this block.

am I supposed to be putting something at the top above option1() to reference this block of code at the bottom to start it from here first so that it knows to look at the definitions when end-user selects 1-5?
You are right. The functions must be defined before they are called. The full example could be:
def option_one():
    print('Option 1 processed.')

def option_two():
    print('Option 2 processed.')

def option_four():
    print('Option 4 processed.')
    
user_exit = 5
while True:
    #prints statements that lead the end-user to decide what they would like to do
    print('Welcome to the ROWriter Database applet! What would you like to do?')
    print()
    print('1) Insert a new store CIM info...')
    print('2) Update an existing store CIM info...')
    print('3) Delete an existing store CIM info...')
    print('4) Search for CIM')
    print('5) Exit the application...')

    #accepts user input and converts it to a string and stores into a variable
    user_input = int(input('Enter option:'))
    #if user input is equal to the exit variable then the application exits
    if user_input == user_exit:
        break
    elif user_input == 1:
        option_one()
    elif user_input == 2:
        option_two()
    elif user_input == 4:
        option_four()

Open in new window

When Python launches the script, it simply executes the commands from top to bottom. If a function definition is found, then the execution means building an internal object that implements the defined functionality. The code outside a function definition is compiled to bytecode and launched. There is no need to put any special reference to the block at the bottom.  Think as if the text was directly interpreted (even though it is first compiled to the bytecode).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial