-3

I want to use a switch in python how may i use it. Suppose if i want to assign a marking system for students above 90 marks will get grade A below that will get B using switch

Please help!!!

  • 1
    If that's your criteria, above 90 is an A and below is a B, then a switch wouldn't be the appropriate tool even if it did exist in Python. – khelwood Sep 01 '20 at 09:09
  • 1
    you can use if-else here, for switch please refer https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python – manask322 Sep 01 '20 at 09:10

2 Answers2

0

Python doesn't have a switch statement. To implement similar functionality in Python, you can use if/elif/else (which would work nicely for your example) or a look-up table using a dictionary.

Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
0

you can simulate a switch statement using the following function definition:

def switch(v): yield lambda *c: v in c

You can use it in C-style:

x = 3
for case in switch(x):

    if case(1):
        # do something
        break

    if case(2,4):
        # do some other thing
        break

    if case(3):
        # do something else
        break

else:
    # deal with other values of x

Or you can use if/elif/else patterns without the breaks:

x = 3
for case in switch(x):

    if case(1):
        # do something

    elif case(2,4):
        # do some other thing

    elif case(3):
        # do something else

    else:
        # deal with other values of x

It can be particularly expressive for function dispatch

functionKey = 'f2'
for case in switch(functionKey):
    if case('f1'): return findPerson()
    if case('f2'): return editAccount()
    if case('f3'): return saveChanges() 
Alain T.
  • 40,517
  • 4
  • 31
  • 51