Search notes:

Python: if statement

if

if 'one' < 'two':
    print('one < two')
Github repository about-Python, path: /statements/if/simple.py

if … else

if 'one' < 'two':
   print('one < two')
else:
   print('one >= two')
Github repository about-Python, path: /statements/if/else.py

else if

Python uses the shortcut elif for else if:
a = 1
b = 1

if   a < b:
     print('a < b' )

elif a > b:
     print('a > b' )

else:
     print('a == b')
Github repository about-Python, path: /statements/if/elif.py

Ternary operator

The ternary operator … ? … : …, as found in C related languages, can be simulated in Python with … if … else …:
val = 42
result = 'yes' if val == 42 else 'no'
print(result)

val = 99
result = 'yes' if val == 42 else 'no'
print(result)
Github repository about-Python, path: /statements/if/ternary.py

Assignment in if statement

PEP-572 defines the assignment expression (aka walrus operator) with which it is (finally) possible to have an assignment in an if statement:
def half(n):

    r = n/2
    return r if int(r) == r else None


def F(n):

    if h := half(n):
       print('half({}) = {}'.format(n,h))
    else:
       print('{} is odd'.format(n))


F(42)
F(99)
Github repository about-Python, path: /statements/if/assignment.py

Using if in list comprehensions

if can also be used in list comprehensions to select the elements in a list that meet the given condition:
result = [ expr(x) for x in someList if criterion(x)]

See also

Each object can be evaluated in a boolean context, such as an if or while statement. The rules if an object is considered to be True or False are described here.
The else clause
statements

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758199880, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/statements/if/index(116): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78