Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

switch statement doesnt execute in function call

I’m trying to get input from users that will be used in a function call channel that I created. In the start function I called function channel however it doesnt execute the function called and end the code there with printed selected channel.

# global vars
channelArr = ['1','2']

# func channel 1
def getChOne():
    print('Do something with channel 1')

# func channel 2
def getChTwo():
    print('Do something with channel 2')

# func channel
def channel(arg):
    switcher = { 
        1: lambda: getChOne(),
        2: lambda: getChTwo(),
    }
    return switcher.get(arg, lambda: "Invalid Channel")

# func start
def start():
    # get input
    print('\n')
    inputChannel = input('Channel 1 to 2: ')

    # check input 
    if (inputChannel.strip() in channelArr):
        print('Selected Channel:', inputChannel.strip())
        channel(inputChannel.strip())      
    else:
        exit()

# init app
if (__name__ == '__main__'):
    # call func start
    start()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are multiple issues here.

  1. Your code does call channel() but it returns a lambda which you never use (call)
  2. In your switcher dict keys are int and you pass str as argument (i.e. the lambda returned in 1. is always the one with Invalid Channel.
  3. because in the if statement you check that user input is in channelArr, normally (i.e. if you fix the keys in switcher) there should be no need to use get() with fall-back value).
  4. Actually you don’t need lambda in swithcher

# func channel 1
def getChOne():
    print('Do something with channel 1')

# func channel 2
def getChTwo():
    print('Do something with channel 2')

# func channel
def channel(arg):
    switcher = { 
        '1': getChOne,
        '2': getChTwo,
    }
    return switcher.get(arg, lambda: print("Invalid Channel"))

# func start
def start():
    inputChannel = input('Channel 1 to 2: ').strip()
    print('Selected Channel:', inputChannel)
    channel(inputChannel)()  # call the function  

if (__name__ == '__main__'):
    # call func start
    start()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading