⊗pyPmCdBShI 139 of 208 menu

Shortened if in if-else construct

The if-else construction can be used in a shortened form if we need to check whether a variable is true. In a broad sense, this means whether the variable is equal to the Boolean value True. In the short form, after if, it is enough to simply write the variable name without any conditions for comparison:

tst = True if tst: print('+++') # this will work else: print('---')

You can also use the shorthand if when the variable has values ​​equal to Boolean ones.

Values ​​that evaluate to False

  • None
  • integer 0
  • floating point number 0.0
  • empty string ''
  • empty list []
  • empty tuple ()
  • empty dictionary {}
  • empty set set()

All other values ​​are set to True.

Let's check if the variable tst is equal to the value True:

tst = 5 if tst: print('+++') # this will work else: print('---')

Tell me what will be the result of executing this code:

tst = [] if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = None if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = -1 if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = False if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = True if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = 'False' if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = '0' if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = () if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = [0] if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = 1 - 1 if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = {} if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = set() if tst: print('+++') else: print('---')

Tell me what will be the result of executing this code:

tst = '' if tst: print('+++') else: print('---')
byenru