How to reduce if else statement in python

All you need to do in this case is construct a string from the integer value self.timeselect.get().

selectedchoice = self.timeselect.get()
if 0 < selectedchoice < 73:
    orig_stdout = sys.stdout
    f = open('missing_time.txt', 'w')
    sys.stdout = f
    print( str(selectedchoice).zfill(4) )     # Convert choice to 
                                              # string with leading
                                              # zeros to 4 charaters
    f.close()

Further in the interests of simplification, redirecting stdout and restoring it is a cumbersome method of outputting to a file. Instead, you can write directly to the file:

    with open('missing_time.txt', 'w') as f:
        f.write(selectedchoice + "\n")

Note that because we use the with context manager here, f is automatically closed when we leave this context so there is no need to call f.close(). Ultimately you end up with:

selectedchoice = self.timeselect.get()
if 0 < selectedchoice < 73:
    with open('missing_time.txt', 'w') as f:
        f.write( str(selectedchoice).zfill(4) + "\n" )

Even if you did use the conditionals each one differs only in the first line, so only that part need be conditional and the remainder of the content performed after the conditionals. Moreover all conditionals are mutually exclusive so you can use else-if:

    if self.timeselect.get() == 1:                
        selectedchoice = "0000"

    elif self.timeselect.get() == 2:                
        selectedchoice = "0020"

    ...

    if 0 < selectedchoice < 73:
        with open('missing_time.txt', 'w') as f:
            f.write(selectedchoice + "\n")

In circumstances where there is no direct arithmetic relationship between selectchoice and the required string, or the available choices are perhaps not contiguous, it is possible to implement a switch using a dictionary:

choiceToString = {
    1:  "0001",
    2:  "0002",
    ...
    72: "0072",
}

selectedchoice = choiceToString.get( self.timeselect.get(), "Invalid Choice")

if selectedchoice != "Invalid Choice":
    with open('missing_time.txt', 'w') as f:
        f.write(selectedchoice + "\n")

If/Elif/Else statements should not be verbose and long lines of code.

Photo by Victoriano Izquierdo on Unsplash

If Statement is a primary logic method in Python and we can find them everywhere in Python code. As a beginner, you often write long lines of code to check if something is the case and execute something based on the result of the condition.

If statements are great tools, but as the number of branches grows, they quickly become unwieldy. In this article, we will explore two alternatives to if statements:

  • "match...case", a new Python 3.10 language feature.
  • Dictionaries, particularly useful when dealing with user input.

This article's scenario: a long if statement

Imagine you have an if statement like this one (assume the average function has already been defined):

numbers = [1, 4, 16, 20]
action = input(f"What would you like to do with {numbers}?")  # e.g. add

if action == "add":
    print(sum(numbers))
elif action == "avg":
    print(average(numbers))
elif action == "max":
    print(max(numbers))
else:
    print("Action not recognized")

Using match...case to simplify an if statement chain

In "match...case", we still need to tell Python what the different options are, and what to do in each case:

def average(seq):
	return sum(seq) / len(seq)

numbers = [1, 4, 16, 20]
action = input(f"What would you like to do with {numbers}? ")

match action:
	case "add":
		print(sum(numbers))
	case "avg":
		print(average(numbers))
	case "max":
		print(max(numbers))
	case _:
		print("Operation not recognized.")

While this looks a bit better, there is still much of the same duplication. Each conditional branch has the print() function duplicated, and there are a lot of keywords.

Overall, the length of the code block is the same.

Plus the biggest problem of all remains: that as you add more options, the branching conditional will grow too.

Use a dictionary to simplify a long if statement

Instead of the log if-elif chain or a long match-case chain, you could store the user's options in a dictionary:

options = {
    "add": sum,
    "avg": average,
    "max": max
}

Then you could ask the user for which of the options (from the dictionary) they'd like to use:

options = {
    "add": sum,
    "avg": average,
    "max": max
}
numbers = [1, 4, 16, 20]

action = input(f"What would you like to do with {numbers}?")  # e.g. add

With this, we can retrieve the function from the dictionary directly:

options = {
    "add": sum,
    "avg": average,
    "max": max
}
numbers = [1, 4, 16, 20]

action = input(f"What would you like to do with {numbers}?")  # e.g. add

operation = options.get(action)

Since the dictionary maps strings to functions, the operation variable would now contain the function we want to run.

All that's left is to run operation(numbers) to get our result. If the user entered 'add', then operation will be the sum function.

We should also do some error checking, to make sure we don't try to run a function that doesn't exist if the user entered something that isn't one of the dictionary's keys.

options = {
    "add": sum,
    "avg": average,
    "max": max
}
numbers = [1, 4, 16, 20]

action = input(f"What would you like to do with {numbers}?")  # e.g. add

operation = options.get(action)

if operation:
    operation(numbers)
else:
    print("Action not recognized")

You still need the one if statement just in case the user chooses something that doesn't have a key in the dictionary, but this is a single-branch if statement that won't grow over time.

Another benefit is that you can easily tell the user which options are available to them by using the dictionary keys:

option_texts = '|'.join(options.keys()
action = input(f"What would you like to do with {numbers}? ({option_texts}) ")
# Would show "What would you like to do with [1, 4, 16, 20]? (add|avg|max) "

Conclusion

In this post we've seen two ways you can simplify if statements: by using "match...case" and by using dictionaries.

If you want to learn more about Python, consider enrolling in our Complete Python Course which takes you from beginner all the way to advanced (including OOP, web development, async development, and much more!). We have a 30-day money-back guarantee, so you really have nothing to lose by giving it a try. We'd love to have you!

Photo by Christin Hume on Unsplash

How do you reduce if

4 Simple and Effective Ways To Avoid Too Many Ifs With TypeScript.
Nested if-else or multiple level nesting (worse).
Too many if-elses cause large numbers of condition branches..
Complex condition statement with mixed flags..

How do you shorten a long if statement in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

How do you optimize multiple if

3 Answers.
Using Explicit and for Logical Expressions. ... .
Remove Redundant Conditions. ... .
Avoid Repeated Computations in Conditions. ... .
Simplify Logic. ... .
Apply Python-specific Optimizations. ... .
Adjust Order of Conditions based on Input Distribution. ... .
Using Lookup Tables..

What can be used instead of if

Switch Case is a cleaner and faster alternative to if-else conditions in your code. Python does not directly support Switch Case but it does provide some very useful and efficient workarounds.