2

I am fairly new to programming, and at the moment am creating a program with many different functions. At the moment, the user has to type in a command, such as 'time', or 'help', without the function brackets. I would like it to stay that way.

But my code for this is very inefficient:

x=input()
if x=='time':
    time()
elif x=='date':
    date()

At the moment it seems short, but I plan to have many functions. Is there a way to make a loop which does all of this?

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73

1 Answers1

2

Keep all the functions in a list, and traverse through list using for loop.

In your example:

def time():
      print "this is time function"
def date():
      print "this is date function"
list1 = [date, time]
x = raw_input()
for foo in list1:
  if foo.__name__ == x:
       foo()

Output:

$ python new1.txt 
date
this is date function
$ python new1.txt 
time
this is time function
user3270602
  • 696
  • 7
  • 15