0

i am struggling to get a switch case program in python,when i run the script i want to display three options

Enter your choice :

1.Insert Records

2.Update Records

3.Display Records

and after seeing these,the user should be able to enter his choice.Since am new to python i googled and found that there is no switch case in python.

def main():
    print("Enter your choice : ")
    print("1.Insert Records \n2.Update Records \n3.Display Records")
    choice = sys.argv[1]
    if(choice == 1):
        print 1
    if(choice == 2):
        print 2
    if(choice == 3):
        print 3
    else:
        print("You entered a wrong choice")

if __name__ == "__main__":
    main()

This is what i tried but its of no use, because it needs to enter choice at the time of running the script(eg. python abc.py 1)

kuro
  • 3,214
  • 3
  • 15
  • 31
tintin
  • 35
  • 2
  • 12

5 Answers5

1

Instead of switch/case, you can use a dict, like this:

from sys import argv

def insertRecord(args):
  ...

def updateRecord(args):
  ...

def displayRecords(args):
  ...

{
  1 : insertRecords,
  2 : updateRecords,
  3 : displayRecords
}[argv[1]](argv[2])

If you want to catch a default case, you can add something like this:

from sys import argv

def insertRecord(args):
  ...

def updateRecord(args):
  ...

def displayRecords(args):
  ...

def printHelp():
  ...

try:
  {
    1 : insertRecords,
    2 : updateRecords,
    3 : displayRecords
  }[argv[1]](argv[2])    
except KeyError:
  printHelp()

Hope this helps.

J. D.
  • 113
  • 13
0

sys.argv is a list of strings. You are trying to compare one of those to integers, and that won't work without conversion.

In this case, you don't need to convert, just compare to strings instead:

if choice == '1':
    print 1
elif choice == '2':
    print 2
elif choice == '3':
    print 3
else:
    print("You entered a wrong choice")

You can still convert the string to an integer first, allowing you to do more complex checks:

try:
    choice = int(sys.argv[1])
except ValueError:
    print("You entered a wrong choice")
else:
    if not 1 <= choice <= 3:
        print("You entered a wrong choice")
    else:
        print(choice)

If you are building an interactive menu, then perhaps the command line options are not the best choice here. Use the input() function instead so you print prompts and use a series of exchanges. See Asking the user for input until they give a valid response.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Look at the description of sys.argv. It is not used for input in runtime. Rather it is used to pass arguments to script when it is called. So this script:

import sys

print sys.argv

When called with python script.py one two three would print ['one', 'two', 'three']

If you want to get user input on executiopn of the program you should use input. Look carefully at the details such as returned value etc.

The next issue as makred by Martijn is that python does not have switch-case. You should use if-elif-else constrcution.

gonczor
  • 3,994
  • 1
  • 21
  • 46
0

It sounds like you want to prompt the user for input. In python 2.x, use raw_input for that. Users enter strings, so I changed what you are looking for. And used elif to end the compares after you find a match.

def main():
    print("Enter your choice : ")
    choice = raw_input("1.Insert Records \n2.Update Records \n3.Display Records")
    if(choice == '1'):
        print 1
    elif(choice == '2'):
        print 2
    elif(choice == '3'):
        print 3
    else:
        print("You entered a wrong choice")

if __name__ == "__main__":
    main()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You are able to pass the choice as argument OR it will ask. I prefer the lambda-version in "switch-cases" to be sure it will only be executed when accessed. This way you can replace print(1) etc. with a performance intense task and it won't run for every entry in the dict.

Python3 example:

import sys
def get_input():
    print("Enter your choice : ")
    return input("1.Insert Records \n2.Update Records \n3.Display Records")

def main():
    choice = sys.argv[1] if len(sys.argv)>1 else get_input()
    {
        '1': lambda: print(1),
        '2': lambda: print(2),
        '3': lambda: print(3),
        '4': lambda: print(4),
        }.get(choice, lambda: print("You entered a wrong choice"))()

if __name__ == "__main__":
    main()

Same in python2:

import sys
def get_input():
    print "Enter your choice : "
    return raw_input("1.Insert Records \n2.Update Records \n3.Display Records")

def print_val(val):
    print val

def main():
    choice = sys.argv[1] if len(sys.argv)>1 else get_input()
    {
        '1': lambda: print_val(1),
        '2': lambda: print_val(2),
        '3': lambda: print_val(3),
        '4': lambda: print_val(4),
        }.get(choice, lambda: print_val("You entered a wrong choice"))()

if __name__ == "__main__":
    main()
Frank
  • 1,959
  • 12
  • 27