i have this long and ugly else if statement in python, is there a way to condense it into a shorter block of code maybe on one line or two if possible because it seems like there would be a way of shortening a piece of code like this
if p == "A": y = 10
elif p == "B": y = 11
elif p == "C": y = 12
elif p == "D": y = 13
elif p == "E": y = 14
elif p == "F": y = 15
The recommended style for multiline if statements in Python is to use parentheses to break up the if statement. The PEP8 style guide recommends the use of parentheses over backslashes and putting line breaks after the boolean and and or operators.
Summary. If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.
Python if statement is one of the most commonly used conditional statements in programming languages. It decides whether certain statements need to be executed or not. It checks for a given condition, if the condition is true, then the set of code present inside the ” if ” block will be executed otherwise not.
Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
have a dictionary containing values of y given p
p={"A":10,.....}
y=dict[p]
There is no possibility to shorten this piece of code. As you may have noticed, python does not provide any switch-case statement.
Depending on your usage, you could change it to a dictionary or recalculate it by value:
values = { "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15 }
y = values[p]
or
y = ord(p) - ord("A") + 10
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