Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python if statement too long and ugly, is there a way to shorten it [duplicate]

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
like image 651
user3854446 Avatar asked Aug 26 '14 13:08

user3854446


People also ask

How do you break a long if statement in Python?

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.

How do you keep a line shorter in Python?

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.

Are if statements Pythonic?

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.

Can you have 2 if statements in Python?

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.


2 Answers

have a dictionary containing values of y given p

p={"A":10,.....}
y=dict[p]
like image 120
user3684792 Avatar answered Sep 26 '22 16:09

user3684792


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
like image 43
roalter Avatar answered Sep 22 '22 16:09

roalter