#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    5
    Rep Power
    0

    Question Simple cli menu quits on selection


    Hello,

    First day on Python

    I was looking to create a simple cli sample menu for my Ubuntu 17.10 and default Python 3.6.3 and i end up to this one:

    Code:
    #!/usr/bin/env python
     
    def menu():
        print ("Welcome, \n 1. Print Hello \n 2. Print World \n 3. Print Python \n 4. Print Hello World")
        choice = input()
     
        if choice == "1":
            print("Hello")
            menu()
     
        if choice == "2":
            print("World")
            menu()
     
        if choice == "3":
            print("Python")
            menu()
     
        if choice == "4":
            print("Hello World")
            menu()
     
     
    menu()
    hen i run it from terminal the menu appear with no issues but when i add a selection it quits to command prompt with no errors

    Any help?

    Thank you
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,888
    Rep Power
    509
    Suppose the input is neither 1, nor 2, nor 3, nor 4.

    All the tests fail, the menu function prints nothing, does not call itself recursively, and returns None.

    This is a poor way to write a menu system. When heavily used it piles itself onto the stack---observe that menu invokes itself before returning, and causes stack overflow.
    Code:
    $ yes 1 | python3 p.py
    Welcome, 
     1. Print Hello 
     2. Print World 
     3. Print Python 
     4. Print Hello World
    Hello
    Welcome, 
     1. Print Hello 
     2. Print World 
    ...
        menu()
      File "p.py", line 9, in menu
        menu()
      File "p.py", line 9, in menu
        menu()
      File "p.py", line 9, in menu
        print ("Welcome, \n 1. Print Hello \n 2. Print World \n 3. Print Python \n 4. Print Hello World")
    RecursionError: maximum recursion depth exceeded while calling a Python object
    $
    You might enjoy
    Code:
    #!/usr/bin/env python
     
    def menu():
        while True:
            print ("Welcome, \n 1. Print Hello \n 2. Print World \n 3. Print Python \n 4. Print Hello World\n q for termination")
    
            choice = input()
         
            if choice == "1":
                print("Hello")
         
            elif choice == "2":
                print("World")
         
            elif choice == "3":
                print("Python")
         
            elif choice == "4":
                print("Hello World")
    
            elif choice.lower() == 'q':
                break
    
            else:
                print('unrecognized input')
    
        print('done')
     
    menu()
    Last edited by b49P23TIvg; October 23rd, 2017 at 03:55 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    5
    Rep Power
    0
    When i run it i am getting:

    Code:
    Traceback (most recent call last):
      File "./menu2.py", line 29, in <module>
        menu()
      File "./menu2.py", line 21, in menu
        elif choice.lower() == 'q':
    AttributeError: 'int' object has no attribute 'lower'
  6. #4
  7. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,888
    Rep Power
    509
    Oh. You must be using python version 2. In python 2 input evaluates the string you enter. The fixed terms of your comparisons have type string. "32" does not equal 32 . Run the program as python3.
    So at the command line, issue which python3
    $ which python3
    /usr/bin/python3
    then change the first line of your file to read (on my system) as
    #! /usr/bin/python3


    Examples of input function in python 2 and 3
    Code:
    $ python
    Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    Anaconda is brought to you by Continuum Analytics.
    Please check out: http://continuum.io/thanks and https://anaconda.org
    >>> print(input())  # I enter 3*2, python prints 6
    3*2
    6
    
    
    
    
    $ python3
    Python 3.5.3 (default, Sep 14 2017, 22:58:41) 
    [GCC 6.3.0 20170406] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print(input())  # I enter an expression.  python3 returns the string.
    324**24+23422
    324**24+23422
    >>>
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    5
    Rep Power
    0
    Perfect it works

    How can i convert that to python 3?

    Code:
    print "Welcome,\n"
    Code:
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print(int "Welcome,\n")
    But that doesn't work also:

    Code:
    print(int "Welcome,\n")
    Thank you
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    5
    Rep Power
    0
    As i can't edit my post i just need to add a new empty line after this:

    Code:
    subprocess.call(["lsb_release", "-d"])
    But it doesn't seems to accept the \n in a few places that i was try...
  12. #7
  13. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,888
    Rep Power
    509
    there's a program called 2to3 which attempts to convert python2 programs to python3. As far as I can tell, and I'm usually correct about this, the python documentation doesn't agree with the implementation. On my system, this works:
    Code:
    subprocess.call(args = ('-d','-i',),   executable='lsb_release')
    Code:
    $ 2to3 --help
    2to3 --help
    Usage: 2to3 [options] file|dir ...
    
    Options:
      -h, --help            show this help message and exit
      -d, --doctests_only   Fix up doctests only
      -f FIX, --fix=FIX     Each FIX specifies a transformation; default: all
      -j PROCESSES, --processes=PROCESSES
                            Run 2to3 concurrently
      -x NOFIX, --nofix=NOFIX
                            Prevent a transformation from being run
      -l, --list-fixes      List available transformations
      -p, --print-function  Modify the grammar so that print() is a function
      -v, --verbose         More verbose logging
      --no-diffs            Don't show diffs of the refactoring
      -w, --write           Write back modified files
      -n, --nobackups       Don't write backups for modified files
      -o OUTPUT_DIR, --output-dir=OUTPUT_DIR
                            Put output files in this directory instead of
                            overwriting the input files.  Requires -n.
      -W, --write-unchanged-files
                            Also write files even if no changes were required
                            (useful with --output-dir); implies -w.
      --add-suffix=ADD_SUFFIX
                            Append this string to all output filenames. Requires
                            -n if non-empty.  ex: --add-suffix='3' will generate
                            .py3 files.
    [code]Code tags[/code] are essential for python code and Makefiles!
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    5
    Rep Power
    0
    Yes it works by separating the arguments and in general no problems but i can't add on that line the new line parameter \n
  16. #9
  17. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,888
    Rep Power
    509
    I cannot comprehend the trouble, if there is one. If there is trouble, please post input (and output, but I think we have similar operating system.)
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo