转载-【Python】Python中的True, False条件判断

本文详细介绍了Python中条件语句的使用方法,并通过实例演示了不同类型变量作为条件时的真假判断标准,包括字符串、元组、列表、字典、None及集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出处:http://blog.csdn.net/fu_zk/article/details/41728773

对于有编程经验的程序员们都知道条件语句的写法:

以C++为例:

  1. if (condition)  
  2. {  
  3.     doSomething();  
  4. }  
if (condition)
{
    doSomething();
}
对于Python中的条件判断语句的写法则是下面的样子:

[python] view plain copy
print ?
  1. if (condition):  
  2.     doSomething()  
if (condition):
    doSomething()
那么对于条件语句中的condition什么时候为真什么时候为假呢?

在C++/Java等高级语言中,如果条件的值为0或者引用的对象为空指针,那么该条件即为False。

在Python中如果condition为 ”,(),[],{},None,set()那么该条件为Flase,否则为True。

下面为Python的测试语句:

1.针对字符串的测试

[python] view plain copy
print ?
  1. >>> condition=  
  2. >>> print ‘True’ if condition else ‘False’  
  3. False  
  4. >>> condition=’test’  
  5. >>> print ‘True’ if condition else ‘False’  
  6. True  
>>> condition=''
>>> print 'True' if condition else 'False'
False
>>> condition='test'
>>> print 'True' if condition else 'False'
True
2.针对原组的测试

[python] view plain copy
print ?
  1. >>> condition=()  
  2. >>> print ‘True’ if condition else ‘False’  
  3. False  
  4. >>> condition=(1,2)  
  5. >>> print ‘True’ if condition else ‘False’  
  6. True  
>>> condition=()
>>> print 'True' if condition else 'False'
False
>>> condition=(1,2)
>>> print 'True' if condition else 'False'
True
3.针对列表的测试

[python] view plain copy
print ?
  1. >>> condition=[]  
  2. >>> print ‘True’ if condition else ‘False’  
  3. False  
  4. >>> condition=[’a’,‘b’]  
  5. >>> print ‘True’ if condition else ‘False’  
  6. True  
>>> condition=[]
>>> print 'True' if condition else 'False'
False
>>> condition=['a','b']
>>> print 'True' if condition else 'False'
True
4.针对字典的测试

[python] view plain copy
print ?
  1. >>> condition={}  
  2. >>> print ‘True’ if condition else ‘False’  
  3. False  
  4. >>> condition={’k’:‘v’}  
  5. >>> print ‘True’ if condition else ‘False’  
  6. True  
>>> condition={}
>>> print 'True' if condition else 'False'
False
>>> condition={'k':'v'}
>>> print 'True' if condition else 'False'
True
5.针对None的测试

[python] view plain copy
print ?
  1. >>> condition=None  
  2. >>> print ‘True’ if condition else ‘False’  
  3. False  
>>> condition=None
>>> print 'True' if condition else 'False'
False
6.针对set()的测试

[python] view plain copy
print ?
  1. >>> condition=set()  
  2. >>> print ‘True’ if condition else ‘False’  
  3. False  
  4. >>> condition.add(’a’)  
  5. >>> print ‘True’ if condition else ‘False’  
  6. True  
>>> condition=set()
>>> print 'True' if condition else 'False'
False
>>> condition.add('a')
>>> print 'True' if condition else 'False'
True


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值