MUD
MUD

Reputation: 121

Executing multiple if statements sequentially in Python?

I am writing a script to manipulate an input file in different ways. The user will specify which method to use: OPTION_1, OPTION_2, or OPTION_3. There is also an option to perform all of these methods sequentially, ALL.

I am having trouble getting the script to continue executing when the ALL option is selected. Here is what I have at the moment:

calculation_type = "ALL"  # ALL, OPTION_1, OPTION_2, OPTION_3

if calculation_type == "ALL":
        print("Calculation type " + calculation_type + " chosen.")

elif calculation_type in {"ALL","OPTION_1"}:
    if calculation_type != "ALL":
        print("Calculation type " + calculation_type + " chosen.")
    # Manipulate file

elif calculation_type in {"ALL","OPTION_2"}:
    if calculation_type != "ALL":
        print("Calculation type " + calculation_type + " chosen.")
    # Manipulate file

elif calculation_type in {"ALL","OPTION_3"}:
    if calculation_type != "ALL":
        print("Calculation type " + calculation_type + " chosen.")
    # Manipulate file


print("Calculation finished") 

This works fine for OPTION_1/2/3, but when the choice is ALL the script gets stuck at the first if statement and does not continue onto the second if statement. How can I make the script execute each if statement sequentially when ALL is selected?

Upvotes: 0

Views: 1402

Answers (2)

chepner
chepner

Reputation: 530970

Without involving sets, you want a straightforward set of three separate if statements. Each explicitly checks for ALL or a specific option.

if calculation_type == "OPTION_1" or calculation_type == "ALL":
    ...
if calculation_type == "OPTION_2" or calculation_type == "ALL":
    ...
if calculation_type == "OPTION_3" or calculation_type == "ALL":
    ...

Using sets, the structure is the same:

if calculation_type in {"OPTION_1", "ALL"}:
    ...
if calculation_type in {"OPTION_2", "ALL"}:
    ...
if calculation_type in {"OPTION_3", "ALL"}:
    ...

Upvotes: 1

Stijn De Pauw
Stijn De Pauw

Reputation: 332

Remove the elif statements and use if. elif is only executed if the previous if fails, which is not the case when the type is ALL.

The following would be more correct:

calculation_type = "ALL"  # ALL, OPTION_1, OPTION_2, OPTION_3

if calculation_type == "ALL":
        print("Calculation type " + calculation_type + " chosen.")

if calculation_type == "OPTION_1":
        print("Calculation type " + calculation_type + " chosen.")
    # Manipulate file

if calculation_type == "OPTION_2":
        print("Calculation type " + calculation_type + " chosen.")
    # Manipulate file

if calculation_type == "OPTION_3":
        print("Calculation type " + calculation_type + " chosen.")
    # Manipulate file


print("Calculation finished")

Upvotes: 1

Related Questions