python - 没有条件的 if 语句

标签 python

def f1(x,y):
      if x:    
          x = [1,2,3]
          x.append(4)
      else:
          x = 2
      return x + y

L1 = [1,2,3]
L2 = [55,66]
L3 = []
y = 3
print( f1(L3,y) )            # Line 1
print( L3 )                  # Line 2
print( f1(L1,L2) )           # Line 3
print( L1 )                  # Line 4

#我想看懂这个表达式,它在说什么? “如果x:”是什么意思?通常在 if 语句之后总是有一个条件,但是这个没有。我怎么理解这个?它在这个功能中做了什么?

最佳答案

就是检查x是真还是假(二进制)。

如果 x:

当 x 值不等于 0(当 x 是一个数字)时返回真,如果它至少有一个字符(当 x 是字符串时)返回真。如果 x 等于 '0' 或 '' 或 'None',则返回 false

例如:

a = 10
if a:
    print a

这会打印“10”

a = 'DaiMaria'
if a:
    print a

这会打印出 'DaiMaria'

a = 0.1
if a:
    print a

打印 0.1

a = 0
if a:
    print a

返回 False 时不打印任何内容。

a = None
if a:
    print a

返回 False 时不打印任何内容。

a = ''
if a:
    print a

返回 False 时不打印任何内容。

关于python - 没有条件的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43063267/

相关文章:

python - Python-Ply分析器: How can I stop the parsing wherever I want?

python - 让 PyQt5 + venv + qt5ct 正常运行时遇到问题

python - 在 python 中使用 dict 作为 switch 语句

python - 如何使用python在日历中突出显示今天的日期

python - 一定时间后自动关闭窗口

Python 正则表达式将列表解析为文本以进行响应

Python字典: Return First Value in List Or String

Python Pandas 绘制由 secondary_y 更改的图层顺序

python - 通过字典访问函数

python - 安装 Python 的多个主要版本和位版本