Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write nested if statements in python? [closed]

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.

like image 754
Module_art Avatar asked Nov 19 '19 06:11

Module_art


People also ask

What can I use instead of nested if statements in Python?

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 .

Are nested if statements bad practice Python?

statements are fine, so long as they are logical and easy to read/maintain.

When should we use nested if statements in Python?

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.

How do you avoid long nested if statements?

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.


1 Answers

Insert all the valid combinations to a dictionary of tuples, 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.

like image 52
Aryerez Avatar answered Sep 17 '22 21:09

Aryerez