If the number is odd, divide it by 2 and subtract 10.īut let’s then take a look at what happens when you turn it into a one-liner expression: result = x * 2 + 10 if x % 2 = 0 else x / 2 - 10 If x is even, multiply it by 2 and add 10 to it. Let’s see a bad example of a one-liner if-else statement as well.įirst, let’s use a regular if-else approach: x = 1 You already saw a bad example of a lengthy one-liner if-elif-else statement in the previous section. So think twice before breaking your Python if-else on one line. This is to preserve the readability and expressibility of the code. They should not be used with longer statements. One-line if-else statements should only be used with simple expressions (identifiers, literals, and operators). This is because it is up to a debate as to whether it improves code quality or not. Some people do not use one-liner if-else statements at all. It is way cleaner to write the above expression like this: n = 10 As you can see from the above, it only makes the code less readable. To write an if-else statement on one line, follow the conditional expression syntax: some_expression if condition else other_expressionīut please, do not do this. In Python, you can have if-else statements on one line.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |