Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python statement of short 'if-else'

Is there a Python version of the following if-else statement in C++ or similar statement like this:

  int t = 0;   int m = t==0?100:5; 
like image 313
icn Avatar asked Dec 14 '11 06:12

icn


People also ask

How do you shorten an if-else statement?

Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy.

How do you write an if-else statement in Python?

Here's an example:if 51<5: print("False, statement skipped") elif 0<5: print("true, block executed") elif 0<3: print("true, but block will not execute") else: print("If all fails.")

What is Elif short for in Python?

The elif keyword is used in conditional statements (if statements), and is short for else if.

What are the 3 types of Python conditional statements?

Python Conditional Statements: If, Else & Switch.


2 Answers

m = 100 if t == 0 else 5 # Requires Python version >= 2.5 m = (5, 100)[t == 0]     # Or [5, 7][t == 0] 

Both of the above lines will result in the same thing.

The first line makes use of Python's version of a "ternary operator" available since version 2.5, though the Python documentation refers to it as Conditional Expressions.

The second line is a little hack to provide inline functionality in many (all of the important) ways equivalent to ?: found in many other languages (such as C and C++).


Documentation of Python - 5.11. Conditional Expressions

like image 72
Filip Roséen - refp Avatar answered Sep 23 '22 03:09

Filip Roséen - refp


The construct you are referring to is called the ternary operator. Python has a version of it (since version 2.5), like this:

x if a > b else y 
like image 21
bobbymcr Avatar answered Sep 24 '22 03:09

bobbymcr