Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a simple if-then-else statement on one line [duplicate]

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.

like image 652
Abizern Avatar asked May 10 '10 12:05

Abizern


People also ask

How do you write if else on the same line?

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.

How do you write if condition in one line?

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!

Can we write else if statement into one line in Python?

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.

What is the format of if/then else?

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 .


1 Answers

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 
like image 61
cmsjr Avatar answered Dec 09 '22 14:12

cmsjr