Python statement of short 'if-else'


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

  int t = 0;
  int m = t==0?100:5;
Asked By: icn



t = 0
if t == 0:
  m = 100
  m = 5

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.

From PEP 20.

Or if you really, really must (works in Python >= 2.5):

t = 0
m = 100 if t == 0 else 5
Answered By: Dominic Rodger

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
Answered By: bobbymcr
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

There is also:

m = t==0 and 100 or 5

Since 0 is a falsy value, we could write:

m = t and 5 or 100

This is equivalent to the first one.

Answered By: yilmazhuseyin

I find the first shorthand handy in keyword pass-in. Example below shows that it is used in tkinter grid geometry manager.

class Application(Frame):
    def rcExpansion(self, rows, cols, r_sticky, c_sticky):
        for r in range(rows):
            self.rowconfigure(r, weight=r)
            b = Button(self, text = f"Row {r}", bg=next(self.colors))
            b.grid(row=r, column= 0, sticky = N+S+E+W if r_sticky == True else None)
        for c in range(cols):
            self.columnconfigure(c, weight=c)
            b = Button(self, text = f"Column {c}", bg=next(self.colors))
            b.grid(row=rows, column = c, sticky = N+S+E+W if c_sticky == True else None)

app = Application(root=Tk())
app.rcExpansion(3, 4, True, False)
Answered By: Leon Chang

for print statement

a = input()

b = input()

print(a) if a > b else print(b)
Answered By: Abdulrahman M
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.