Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-equivalent of short-form "if" in C++ [duplicate]

Tags:

c++

python

syntax

Possible Duplicate:
Python Ternary Operator

Is there a way to write this C/C++ code in Python? a = (b == true ? "123" : "456" )

like image 608
huy Avatar asked Nov 06 '09 09:11

huy


People also ask

How do you write a short IF statement in Python?

Python's short-hand method for writing an if/else statement There are three components to the ternary operator: the expression/condition, the positive value, and the negative value. When the expression evaluates to true, the positive value is used—otherwise the negative value is used.

Is there ?: In Python?

Ternary operators are also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

How do you write if-else in the same line 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.

What is ternary conditional operator in Python?

Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.


2 Answers

a = '123' if b else '456' 
like image 183
SilentGhost Avatar answered Sep 28 '22 14:09

SilentGhost


While a = 'foo' if True else 'bar' is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:

a = (b == True and "123" or "456" ) 

... which in python should be shortened to:

a = b is True and "123" or "456" 

... or if you simply want to test the truthfulness of b's value in general...

a = b and "123" or "456" 

? : can literally be swapped out for and or

like image 26
jdi Avatar answered Sep 28 '22 15:09

jdi