I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if
-then
-else
statement so it fits on one line?
For example:
if count == N: count = 0 else: count = N + 1
Is there a simpler way of writing this? I mean, in Objective-C I would write this as:
count = count == N ? 0 : count + 1;
Is there something similar for Python?
Update
I know that in this instance I can use count == (count + 1) % N
.
I'm asking about the general syntax.
One Line If-Else Statements in Python Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.
0 : count + 1; ? For this specific case: count = (count+1) % (N+1) would work. if 1==1: print('hi') can be just used like that. And '''if 1==1: print('hi')''' will print nothing!
Python If Statement In One Line In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.
The if / then statement is a conditional statement that executes its sub-statement, which follows the then keyword, only if the provided condition evaluates to true: if x < 10 then x := x+1; In the above example, the condition is x < 10 , and the statement to execute is x := x+1 .
That's more specifically a ternary operator expression than an if-then, here's the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple' isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple' isApple = False if fruit == 'Apple' : isApple = True
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