Search code examples
pythonsimplify

How can I perform the same statement if it passes one or more if statements?


I want to perform the same task if it passes a chain of if-elif statements.

Presented below is an example of what I am trying to achieve. The program runs bug free, but I was wondering if there was a simpler method to assign continue_program to Yes without typing it out multiple times if it meets one of the conditions.

word_form = "A string!"
continue_program = "No"

number = 2

if number == 1:
    word_form = "one"
    continue_program = "Yes"
elif number == 2:
    word_form = "two"
    continue_program = "Yes"
elif number == 3:
    word_form = "three"
    continue_program = "Yes"


Solution

  • This might be a little too concise:

    d = {1: "one", 2: "two", 3: "three"}
    
    continue_program = bool(word_form := d.get(number, "")))
    

    Look up number in d, which will result in either the desired string or the empty string. As a side effect, assign that string to word_form. The boolean value of that string is further assigned to continue_program.

    Some examples; first, number == 6:

    >>> bool(word_form := d.get(6, ""))
    False
    >>> word_form
    ''
    

    Now, number == 1:

    >>> bool(word_form := d.get(1, ""))
    True
    >>> word_form
    'one'
    

    Update: use a conditional expression to map True/False to "Yes"/"No""

    continue_program = "Yes" if (word_form := d.get(number, "")) else "No"
    

    Pre-3.8,

    word_form = d.get(number, "")
    continue_program = "Yes" if word_form else "No"