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.
- Your code does call
channel()
but it returns a lambda which you never use (call) - In your
switcher
dict keys areint
and you passstr
as argument (i.e. the lambda returned in 1. is always the one withInvalid Channel
. - because in the if statement you check that user input is in
channelArr
, normally (i.e. if you fix the keys inswitcher
) there should be no need to useget()
with fall-back value). - 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()