user7454726
user7454726

Reputation:

Using a loop to make if statements

In a project I am making, there is a list printed out like so

1. A
2. B
3. C
4. D

and so on, continuing up to 23. I am having having the user enter a selection based on the number, and then from there my program runs additional code, like so

entry = str(input())
if entry == '1':
    do_something
if entry == '2':
    do_something_else
if entry == '3':
    do_another_something

and this continues all the way until the 23rd selection. I realize I could type out each if statement, and brute force my way to the last if statement, but this feels quite repetitive, and I was wondering if there was a simplified solution to doing something like this (although I know this is not correct, simply an example)

for number in range(23):
    if entry == number:
        do_something

Perhaps a better explanation would be, I want to create a loop that creates if-statements for me.

Thanks for any help!

Upvotes: 0

Views: 24

Answers (1)

AChampion
AChampion

Reputation: 30258

You still need to describe the mapping from input to behaviour, you could do this as a dictionary. This assumes do_something... are functions that take no args:

dispatch = {
    '1': do_something,
    '2': do_something_else,
    '3': do_another_something,
    ...
}

entry = input()
dispatch[entry]()     

If the functions were called do_something_<input> then you could do something dangerous without the mapping like:

fn = eval("do_something_{}".format(input()))
fn()

Upvotes: 1

Related Questions