美文网首页
Python 条件运算符

Python 条件运算符

作者: FaiChou | 来源:发表于2016-04-11 13:23 被阅读450次

Python程序设计语言使用一种不同的语法处理条件表达式:

valueTrue if condition else valueFalse

这一特性在Python 2.5以前的版本并不可用。
Guido van Rossum(Python的最初设计者及主要架构师)起初认为C?X:Y这样的功能容易出错而未将此功能加入Python,不过后来有许多程序员试图用C and [X] or [Y]来代替之,貌似这是未完全正确的方法。
面对种种问题,吉多·范·罗苏姆最终采用了X if C else Y的方法。links..

(C and [X] or [Y])非官方用法:

>>> 1 and 'z' or 'h'
'z'
>>> 0 and 'z' or 'h'
'h'
>>> a = ''
>>> b = 'h'
>>> 1 and a or b # wrong?
'h'
>>> (1 and [a] or [b])[0] # solusion
''
>>> 

题目:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示
程序代码:

# -*- coding: UTF-8 -*-
score = int(raw_input('input score:'))
# grade = 'A' if score>=90 else 'B' if score>=60 else 'C' #标准方法
grade = score>=90 and 'A' or score>=60 and 'B' or 'C'
print '%d belongs to %s' % (score, grade)

相关文章

网友评论

      本文标题:Python 条件运算符

      本文链接:https://www.haomeiwen.com/subject/uyrilttx.html