0

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!

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Since each if statement does something different, I would have to create a function for each one. In the end, I would still have to brute force my way through either functions or if statements, if my thinking is correct. Sadly I'm probably going to have to just stick with the if statements. Thanks for the help anyway!
Without seeing what the do_something_XXX actually do, it's hard to help further - I'm assuming that they actual do something different dependent on the input. Not sure what you were hoping to be able to do. Still think the dispatch dict is cleaner than all the if statements.
The dictionary is a better choice; it's cleaner (IMHO), and if any two choices have the same action, you can easily reuse a function.
The do_something would simply print out various information. I'm creating a program that allows me to sift through crafting formulas for a game, such as "a stick and a string makes a bow," or "2 sticks and 2 string makes a fishing rod."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.