使用Python的判断语句模拟三目运算

python教程评论1.5K views阅读模式

下面说的和三目运算有点相似,但又不一样,实在不知道该如何拟定标题,先就是这个标题吧,大家都知道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的判断语句模拟三目运算

  • 相关标签:Python
  • 本文原创发布php教程 ,转载请注明出处,感谢您的尊重!
    • 上一篇:在Python中使用lambda高效操作列表的教程
    • 下一篇:整理Python最基本的操作字典的方法

    相关文章

    相关视频

    • 在Django框架中运行Python应用全攻略
    • 在Python的Django框架中创建和使用模版
    • python获取元素在数组中索引号的方法
    • 浅谈python中截取字符函数strip,lstr...
    • 使用Python的判断语句模拟三目运算
    • Python 简介
    • Python 环境搭建
    • Python 中文编码
    • Python 基础语法
    • Python 变量类型

    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论

  • 立即提交

    专题推荐

    企鹅博客
    • 本文由 发表于 2019年8月22日 00:35:53
    • 转载请务必保留本文链接:https://www.qieseo.com/335899.html

    发表评论