带方括号的if语句

2024-06-17 13:04:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道有方括号和没有方括号的区别是什么

这是我在if语句中没有方括号的代码,答案是正确的

a=[3,90,3,7,8,100]
if sum(a)<100:
    a.append(2)
print(a)

如果我用方括号,那就错了,有人能给我解释一下吗

a=[3,90,3,7,8,100]
if [sum(a)<100]:
    a.append(2)
print(a)

Tags: 答案代码if语句sumprintappend区别
3条回答

因此,当您使用方括号时,python会检查列表是否为空,而不是列表中的值

这总是被解释为正确的,因此结果是错误的

强调这一点的例子:

l = [True]
if l:
    print("test")

l = [False]
if l:
    print("test")

两个案例都将打印“test”

检查列表是否为空。请参见下面的说明

>>> [sum(a)<100]
[False]
>>> if [False]:
...   print('hello')
...
hello
>>> if []:
...   print('hello')
...
>>>
a=[3,90,3,7,8,100] # in python lists are denoted by square brackets
if sum(a)<100:  # Here sum(a) means sum([3,90,...]) it's a list and it can add all. 
    a.append(2) # append means adding new element at end of the list a
print(a)
a=[3,90,3,7,8,100] 
if [sum(a)<100]: # here the condition will be always true because [True] is not empty
    a.append(2)
print(a)

相关问题 更多 >