3

Weird things in Python

 2 years ago
source link: https://jyzhu.top/2021/10/25/Weird-things-in-Python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Short Circuit

  • a and b evaluates to a if a is falsey, otherwise it evaluates to b
  • a or b evaluates to a if a is truthy, otherwise it evaluates to b
  • not a evaluates to True if a is falsey, otherwise it evaluates to False
>>> 0 and 'Hello' 0
>>> 'x' and 'y' 'y'
>>> '' or 0
0
>>> -23 or False -23
  • True is represented as 1, and False is represented as 0.
>>> True == 1 
True
>>> False == 0
True
>>> False == ''
False # because False == 0, but 0 != '', because '' == ord('')

Different Behavior in shell/script

>>> n1, n2 = 1234e23, 1234e23
>>> id(n1), id(n2)
(4317529008, 4317529008)

>>> n1 = 1234e23
>>> n2 = 1234e23
>>> id(n1), id(n2)
(4318748880, 4318749104)

The one line if:

  1. don't have an else: if True: print('xxx')

  2. have an else and assign the value: x = 1 if True else 0

    can't say else x = 1.

  3. have an else and don't wanna assign: dirty hack: ignore the returning value:

    x = 1 if False else print(0), the print will return None to x.

    print(1) if True else print(0), normally do.

ls[:] = [1, 2, 3] To change a list in a function

def changeLS(ls):
ls[:] = [1, 2, 3]
ls = [4,5,6]
changeLS(ls)
print(ls)
# ls = [1,2,3] then.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK