Andrew
Andrew

Reputation: 33

Make a function to call while the program is running

For example, I have a program that can add letters and remove letters from list. Here's the code:

my_list = ['a', 'b', 'c', 'd', 'e', 'f']

do = input("Press 'a' to append and 'r' to remove: ")

if do == 'a':
    letter = input("Enter a letter to append: ")
    my_list.append(letter)
    print (my_list)

elif do == 'r':
    letter = input("Enter a letter to append: ")
    my_list.remove(letter)
    print (my_list)

else:
    print ("Something gone wrong...")

To remove a letter from list I have to tell the program what I'm going to do and then it asks me for a letter to remove. Is there any possible way to call my own function (just to make it easier to use the program) like this:

def removing(letter):
    my_list.remove(letter)
    print (my_list)

To use the function in console like this:

What are you going to do? removing(b)

Upvotes: 3

Views: 123

Answers (2)

Jared Goguen
Jared Goguen

Reputation: 9010

For fun, you could expand the answer from @timgeb to accept multiple arguments at once.

my_list = ['a', 'b', 'c', 'd', 'e', 'f']

choices = {'remove': my_list.remove,
           'append': my_list.append}

def call_choice(name, *args):
    for arg in args: 
        choices[name](arg)

print my_list
while True:
    try:
        input_string = raw_input('append <x> OR remove <x>\n')
        call_choice(*input_string.split())
    except (KeyError, ValueError):
        print('something went wrong...')
    print my_list

Demo:

['a', 'b', 'c', 'd', 'e', 'f']
append <x> OR remove <x>
append a b c d e f g
['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove a b c
['d', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove a
['d', 'e', 'f', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove d
['e', 'f', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove e f b c d e f g
[]

Upvotes: 3

timgeb
timgeb

Reputation: 78700

Here's a somewhat restructured suggestion. It asks the user to either input

append something

or

remove something

my_list = ['a', 'b', 'c', 'd', 'e', 'f']

choices = {'remove': my_list.remove,
           'append': my_list.append}

print my_list
while True:
    try:
        choice, item = raw_input('append <x> OR remove <x>\n').split()
        choices[choice](item)
    except (KeyError, ValueError):
        print('something went wrong...')
    print my_list

Demo:

['a', 'b', 'c', 'd', 'e', 'f']
append <x> OR remove <x>
append z
['a', 'b', 'c', 'd', 'e', 'f', 'z']
append <x> OR remove <x>
remove d
['a', 'b', 'c', 'e', 'f', 'z']
append <x> OR remove <x>
remove y
something went wrong...
['a', 'b', 'c', 'e', 'f', 'z']

This should give you an idea/get you started. The dictionary is easily extendable.

Upvotes: 6

Related Questions