Home > Enterprise >  Python - How to count how many If/Else statements exist
Python - How to count how many If/Else statements exist

Time:12-27

I want to count how many If/Else statements are in my function.

My code looks like this:

def countdown(type):
    if type == 1:
        //code
    elif type == 2:
       //code
    else:
        print(f"You have reached the end of the script. "
              f"The maximum type of countdowns are: {x}")
        exit(1)

Where the x is, there should be the number of if queries (If/Else). In this case, there are 3 queries. It should serve that if I create another if/else query within this function, I don't have to change the warning at the bottom of the script.

Is that even possible?

I'm using Python 3.10

CodePudding user response:

Don't use if..else, but a dict or list:

types = {
    1: ...,
    2: ...
}

try:
    types[type]
except KeyError:
    print(f"You have reached the end of the script. "
          f"The maximum type of countdowns are: {len(types)}")
    exit(1)

What exactly to put into the dict as values depends… Can you generalise the algorithm so you just need to put a value into the dict instead of actual code? Great. Otherwise, put functions into the dict:

types = {1: lambda: ..., 2: some_func, 3: self.some_method}

...

types[type]()

CodePudding user response:

Since you are using Python 3.10 you can use a new match operator. An example:

def countdown(type):
    match type:
        case 1:
            # code
        case 2:
            # code
        case _:
            print(f"You have reached the end of the script. "
                  f"The maximum type of countdowns are: {x}")
            exit(1)

As for me, it is a more readable solution than a dict one.

What about counting the number of options, let's consider that we have n different and logically separated options. In this case, I'd advise you an enum:

from enum import IntEnum
class CountdownOption(IntEnum):
    FIRST = 1
    SECOND = 2
    # ...

# ...

def countdown(type):
    match type:
        case CountdownOption.FIRST:
            # code
        case CountdownOption.SECOND:
            # code
        case _:
            print(f"You have reached the end of the script. "
                  f"The maximum type of countdowns are: {len(CountdownOption)}")
            exit(1)
  • Related