How to use Python conditional expression?(Python Conditional Expression)

 

The Python conditional expression is kinda like the ternary operator in other programming languages (condition ? a : b ).

Syntax:

a if condition else b

If condition evaluated to True, a is evaluated and returned, otherwise b is evaluated and returned.

For instance,

a = 1

b = 2

x = a if a < 0 else b

In this case, if a < 0, x will be assigned with the value of a, however this is not the case, so the value of b is assigned to x. So x is 2 instead.


Comments

Popular posts from this blog

How to create a memory puzzle game with Python and Pygame (#005)

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

Introduction to multitasking with Python #003 gevent (2020 tutorial)