使用Python的判断语句模拟三目运算,python语句
使用Python的判断语句模拟三目运算,python语句
下面说的和三目运算有点相似,但又不一样,实在不知道该如何拟定标题,先就是这个标题吧,大家都知道python中没有三目运算,但是and/or有点类似三目运算:
and/or
单独使用表示逻辑关系与和或,也可以组和使用,用法如下
and
and前后如果某一个值为假(False, '', [], {}, None…)则返回第一个假值 如果所有值都为真则返回最后一个真值
or
如果or任意一个值为真,则立刻返回这个值 如果所有值都为假,则or返回最后一个假值
例子
result = 'test' and True # result = True result = 'test' and 'ortest' # result = ortest result = False and 'ortest' # result = False result = '' and None # result = '' result = '' or "Hall" # result = Hall result = False or None # result = None result = 'test' or 'nottest' # result = test
使用单行if else 模拟三目运算
result if True / False else fresult if为真时候结果为result,为假的时候结果为fresult
result = 'test' if True else 'not test' # result = 'test' result = 'test' if False else 'not test' # result = 'not test'
相关内容
- 在Python中使用lambda高效操作列表的教程,pythonlambda
- Python中最常用的操作列表的几种方法归纳,python几种方
- python使用Tkinter显示网络图片的方法,
- python使用PIL缩放网络图片并保存的方法,
- python使用PyGame绘制图像并保存为图片文件的方法,
- python使用PyGame播放Midi和Mp3文件的方法,
- python使用wxPython打开并播放wav文件的方法,
- python使用arp欺骗伪造网关的方法,pythonarp伪造网关
- 在Python中使用mongoengine操作MongoDB教程,mongoenginemongodb
- 利用Python的装饰器解决Bottle框架中用户验证问题,pyt
评论关闭