Is there a more pythonic way to do nested if else statements than this one:
def convert_what(numeral_sys_1, numeral_sys_2): if numeral_sys_1 == numeral_sys_2: return 0 elif numeral_sys_1 == "Hexadecimal": if numeral_sys_2 == "Decimal": return 1 elif numeral_sys_2 == "Binary": return 2 elif numeral_sys_1 == "Decimal": if numeral_sys_2 == "Hexadecimal": return 4 elif numeral_sys_2 == "Binary": return 6 elif numeral_sys_1 == "Binary": if numeral_sys_2 == "Hexadecimal": return 5 elif numeral_sys_2 == "Decimal": return 3 else: return 0
This script is a part of a simple converter.
There are two main ways to make a nested if statement. The first option is to put the if statement inside an if code block. The other option is to place the if statement in the else code of an if/else statement. Python evaluates this nested if statement when the condition of the preceding if statement is True .
statements are fine, so long as they are logical and easy to read/maintain.
This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can.
Nested IFs are powerful, but they become complicated quickly as you add more levels. One way to avoid more levels is to use IF in combination with the AND and OR functions. These functions return a simple TRUE/FALSE result that works perfectly inside IF, so you can use them to extend the logic of a single IF.
Insert all the valid combinations to a dictionary
of tuple
s, and if the combination is not there, return 0:
def convert_what(numeral_sys_1, numeral_sys_2): numeral_dict = { ("Hexadecimal", "Decimal" ) : 1, ("Hexadecimal", "Binary" ) : 2, ("Decimal", "Hexadecimal") : 4, ("Decimal", "Binary" ) : 6, ("Binary", "Hexadecimal") : 5, ("Binary", "Decimal" ) : 3 } return numeral_dict.get((numeral_sys_1, numeral_sys_2), 0)
If you are planning to use the function in a loop, it may be a better idea to define the dictionary outside the function, so it wouldn't be recreated on every call to the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With