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!!!
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!!!
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.
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()