Python Forum
How to write switch case statement in Python
Thread Rating:
  • 2 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write switch case statement in Python
#1
I am new to programming and need help writing the below piece of code in switch-case.
Please HELP.

Thanks in Advance

def pick_day():
'''Inputs day of week and returns the specified day.
'''
day_of_week = input('\nInput Day of the Week as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?\n').title()
if day_of_week == 'Monday':
return 0
elif day_of_week == 'Tuesday':
return 1
elif day_of_week == 'Wednesday':
return 2
elif day_of_week == 'Thursday':
return 3
elif day_of_week == 'Friday':
return 4
elif day_of_week == 'Saturday':
return 5
elif day_of_week == 'Sunday':
return 6
else:
print("\nInvalid Entry, Please try again")
return pick_day()
Reply
#2
There is no case statement in Python. We have good data structures.
You can use for example a dict:

def get_weekday_number(day):
    """
    The function returns the number of weekday for given day.
    Lower case and upper case are allowed.
    """
    days = {
        'Friday': 4,
        'Monday': 0,
        'Saturday': 5,
        'Sunday': 6,
        'Thursday': 3,
        'Tuesday': 1,
        'Wednesday': 2,
        }
    return days[day.title()]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Next time post your code in Python code tags, and if you get errors post full error traceback message in error tags, you can find help here.

What is the problem you are facing with the code?
A common solution for this is to use a dictionary in place of switch-case.
Reply
#4
j.crater

How do I use dictionary to get the same result.

Thanks for your help.
Reply
#5
(May-26-2018, 01:53 PM)pyhelp Wrote: How do I use dictionary to get the same result.
You use code bye @DeaD_EyE,and add your input line as a argument to the function.
def get_weekday_number(day):
    """
    The function returns the number of weekday for given day.
    Lower case and upper case are allowed.
    """
    days = {
        'Friday': 4,
        'Monday': 0,
        'Saturday': 5,
        'Sunday': 6,
        'Thursday': 3,
        'Tuesday': 1,
        'Wednesday': 2,
        }
    return days.get(day.title(), 'Day not found')

day_of_week = input('\nInput Day of the Week as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?\n')
print(get_weekday_number(day_of_week))
Slightly modified with get() method,
the can catch error in input and return Day not found.
Reply
#6
Thank You for your HELP,

The below code works fine but how to handle the error, if a user inputs any month or type anything other than the months listed below.

def pick_month():
        '''returns number for the month given
        '''
        input_month = input('\nInput Month as January, February, March, April, May, or June?\n').title()
        month_of_year = {
            'January': '01',
            'February': '02',
            'March': '03',
            'April': '04',
            'May': '05',
            'June': '06'
            }
        return month_of_year.get(input_month.title(), 'Month not found')
Reply
#7
(May-28-2018, 06:41 PM)pyhelp Wrote: The below code works fine but how to handle the error, if a user inputs any month or type anything other than the months listed below.
You use the same get() method as i showed in previous post you,so it handles error.
A run of your code:
>>> pick_month()

Input Month as January, February, March, April, May, or June?
 April
04

Input Month as January, February, March, April, May, or June?
 car
Month not found

>>> pick_month()

Input Month as January, February, March, April, May, or June?
 12345
Month not found

>>> pick_month()

Input Month as January, February, March, April, May, or June?
 June
06
Reply
#8
There is one more elegant way to achieve the switch-case effect in Python, i.e., using the OOPs concept. You can write a switch class with the following pattern.

1- The switch class shall have a switcher function accepting the choice as an argument.
2- This function will call the getattr() method to map options to functions handling individual cases.
3- The getattr() also takes a default function argument which gets returned when there is no other matching function.
4- You also need to define handlers for every case.

A complete example is given here - Python switch-case using classes and dictionary.
Reply
#9
(Nov-11-2018, 07:02 AM)MeenakshiAgarwal Wrote: There is one more elegant way to achieve the switch-case effect in Python, i.e., using the OOPs concept.
Frankly, both examples are overcomplicated implementation for something that can be written in few lines.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
Quote:Frankly, both examples are overcomplicated
Yes, a simple list will do. This omits the input portion of the code as that is not part of the "case statement".
day_of_week=["Sunday". "Monday", "Tuesday", "Wednesday",
                     "Thursday", "Friday", "Saturday"]
if input_day in day_of_week:
    return day_of_week.index(input_day)
else:
    print("\nInvalid Entry, Please try again")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  switch case not working Username0089098 1 672 Apr-09-2023, 05:49 AM
Last Post: buran
  What colon (:) in Python mean in this case? Yapwc 4 2,051 Dec-28-2022, 04:04 PM
Last Post: snippsat
  Switch case or match case? Frankduc 9 4,385 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  best way to use switch case? korenron 8 2,926 Aug-18-2021, 03:16 PM
Last Post: naughtyCat
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,639 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,834 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  "Switch-to-spreadsheet" entry. Feasible in Python? whatspython 2 1,976 Sep-30-2020, 01:12 PM
Last Post: buran
  How do I do this? Switch Case? mstichler 4 2,501 Jun-05-2020, 10:27 AM
Last Post: snippsat
  How to use switch/case in python? newbieguy 9 3,955 Nov-08-2019, 11:35 AM
Last Post: newbieguy
  How to switch table area coordinates in Python Camelot and Tabula-Py john5 0 4,216 May-08-2019, 04:31 PM
Last Post: john5

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020