领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

Python——选择结构(二十) python 选择结构

nixiaole 2024-11-13 14:08:38 知识剖析 21 ℃

一、单分支选择结构

if 表达式:

语句块

二、双分支结构:

if 表达式:

语句块1

else:

语句块2

三、多分支选择结构

if 表达式1:

语句块1

elif 表达式2:

语句块2

elif 表达式3:

语句块3

else:

语句块4

其中,关键字elif是else if的缩写。

if score > 100 or score < 0:
     return 'wrong score.must between 0 and 100.'
elif score >= 90:
     return 'A'
elif score >= 80:
     return 'B'
elif score >= 70:
     return 'C'
elif score >= 60:
     return 'D'
else:
      return 'F'	

四、选择结构的嵌套

if 表达式1:

语句块1

if 表达式2:

语句块2

else:

语句块3

else:

if 表达式4:

语句块4

degree = 'DCBAAE'
    if score > 100 or score < 0:
        return 'wrong score.must between 0 and 100.'
    else:
        index = (score - 60) // 10
        if index >= 0:
            return degree[index]
        else:
            return degree[-1]

五、三元运算符

  • Python提供了一个三元运算符,并且在三元运算符构成的表达式中还可以嵌套三元运算符,可以实现与选择结构相似的效果。语法为

>>>value1 if condition else value2

  • 当条件表达式condition的值与True等价时,表达式的值为value1,否则表达式的值为value2。

>>> b = 6 if 5>13 else 9 #赋值运算符优先级非常低

>>> b

Tags:

最近发表
标签列表