Home > Enterprise >  switch statement doesnt execute in function call
switch statement doesnt execute in function call

Time:11-15

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

CodePudding user response:

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()
  • Related