[Solved] Python: Raw Input and if statements


It isn’t clear what you’re trying to achieve, but the following might give you some ideas:

def select_formula():
    equations = {frozenset(('a', 'vi', 'd' ,'t')): 'd = vi*t + .5*a*t^2'}
    variables = frozenset(input("Enter the variables to use: ").split())
    try:
        return equations[variables]
    except KeyError:
        return "No formula found"

In use:

>>> select_formula()
Enter the variables to use: a b c
'No formula found'
>>> select_formula()
Enter the variables to use: a d vi t
'd = vi*t + .5*a*t^2'

Points to note:

  • A dictionary is the canonical Python replacement for what could turn into a long series of elifs;
  • The use of frozensets means that user can enter the variables in any order; and
  • The use of str.split() without an argment means any amount of whitespace between variables is tolerated; if you want e.g. comma-separated input, update the split accordingly.

solved Python: Raw Input and if statements