Python - How to count how many If/Else statements exist
I want to count how many If/Else statements I have 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)
wherex
, should have the number of if queries (If/Else).In this case, there are 3 queries.If I create another if/else query in this function, I don't have to change the warning at the bottom of the script.
Is this even possible?
I am using Python 3.10
uj5u.com enthusiastic netizens replied:
Do not useif..else
, use a dictionary or list instead:
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)
Exactly what to put into the dict as values depends...can you generalize this calculus method, so you just need to put a value into the dict instead of the actual code? Great.Otherwise, put the function in a dictionary:
types={1: lambda:..., 2: some_func, 3 : self.some_method}
...
types[type]()
uj5u.com enthusiastic netizens replied:
Since you are using Python 3.10, you can use 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)
For me this is a more readable solution than a font>dict
.
How to count the number of options, let's consider we have n
Different and logically separated options.In this case, I recommend you 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)
0 Comments