(董付国)Python 学习笔记---Python控制结构(1)
第三章 选择与循环
3.1 条件表达式
- 在选择和循环结构中,条件表达式的值只要不是False、0(或0.0、0j等)、空值None、空列表、空元组、空集合、空字典、空字符串、空range对象或其他空迭代对象,Python解释均认为与True等价。
- 从这个意义上讲,几乎所有的Pyhon合法表达式都可以作为条件表达式,包括含有函数调用的表达式。
>>> if 3: #使用整数作为条件表达式
... print(5)
...
5
>>> a = [1,2,3]
>>> if a: #使用列表作为条件表达式
... print(a)
...
[1, 2, 3]
>>> a = [] #空列表
>>> if a:
... print(a)
... else:
... print('empty')
...
empty
常规条件表达式:
>>> i=s=0 #使用关系表达式作为条件表达式
>>> while i<=10:
... s+=i;
... i+=1;
...
>>> print(s)
55
>>> i=s=0
>>> while True: #使用常量True作为条件表达式
... s+=i
... i+=1
... if i>10:
... break
...
>>> print(s)
55
>>> s = 0
>>> for i in range(0,11,1): #遍历迭代对象中的所有元素
... s+=i
...
>>> print(s)
55
- 逻辑运算符and和or以及关系运算符具有惰性求值特点
- 关系运算符也具有短路求值或惰性求值的特点,只计算必须计算的表达式的值。
- 在涉及条件表达式时,如果能够大概率预测不同条件失败的概率,并将多个条件根据“and”和“or”运算的短路求值特性进行组织,可以大幅度提升程序运行效率。下面的函数用来使用用户指定的分隔符将多个字符串连接成一个字符串,如果用户没有指定分隔符则使用逗号。
>>> def Join(chList,sep = None):
... return(sep or ',').join(chList)
...
>>> chTest = ['1','2','3','4','5']
>>> Join(chTest)
'1,2,3,4,5'
>>> Join(chTest,':')
'1:2:3:4:5'
>>> Join(chTest,' ')
'1 2 3 4 5'
- 另外,在Python中,条件表达式中不允许使用赋值运算符“=”,避免了其他语言中误将关系运算符“==”写作赋值运算符“=”带来的麻烦,例如下面的代码,在条件表达式中使用赋值运算符“=”将抛出异常,提示与语法错误。
>>> if a=3:
File "<stdin>", line 1
if a=3:
^
SyntaxError: invalid syntax
>>> if (a=3)and(b=4)
File "<stdin>", line 1
if (a=3)and(b=4)
^
SyntaxError: invalid syntax
3.2.1 单分支选择结构
>>> x = input('Input two number:')
Input two number:4 3
>>> a,b = map(int,x.split())
>>> if a>b:
... a,b=b,a #序列解包,交换两个变量的值
...
>>> print(a,b)
3 4
3.2.2 双分支结构
>>> chTest = ['1','2','3','4','5']
>>> if chTest:
... print(chTest)
... else:
... print('Empty')
...
['1', '2', '3', '4', '5']
- Python还支持如下形式的表达式:
Value if condition else value2
当条件表达式condition的值与True等价时,表达式的值为value1,否则表达式的值为value2.另外,在value1和value2中还可以使用复杂表达式,包括函数调用和基本输出语句。这个结构的表达式也具有惰性求值的特点。
>>> a = 5
>>> print(6) if a>3 else print(5)
6
>>> print(6 if a>3 else 9)
6
>>> b = 6 if a>3 else 9
>>> b
6
条件表达式也具有惰性求值的特点:
>>> x = math.sqrt(9) if 5>3 else random.randint(1,100) #此时还没有导入math模块
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> import math
>>> x = math.sqrt(9) if 5>3 else random.randint(1,100) #此时还没有导入random模 块,但由于条件表达式2>3的值为False,需要计算第二个表达式的值,因此出错
>>> x
3.0
>>> x = math.sqrt(9) if 2>3 else random.randint(1,100) #此时还没有导入random模 块,但由于条件表达式2>3的值为False,需要计算第二个表达式的值,因此出错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'random' is not defined
>>> import random
>>> x = math.sqrt(9) if 2>3 else random.randint(1,100)
>>> x
35
3.2.3 多分支结构
- 利用多分支选择结构将成绩从百分制变换到等级制
>>> def func(score):
... if score>=100:
... return 'wrong score.must<=100.'
... elif score>=90:
... return 'A'
... elif score>=80:
... return 'B'
... elif score>=70:
... return 'C'
... elif score>=60:
... return 'D'
... elif score>=0:
... return 'E'
... else:
... return 'Wrong score.must>0'
注意:缩进必须要正确并且一致
3.2.4 选择结构的嵌套
def func(score):
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]
3.2.5 构建跳转表实现多分支选择结构
- 使用列表、元组或字典可以很容易构建跳转表,在某些场合下可以更快速地实现类似于多分支选择结构的功能。
funcDict = {'1':lambda:print('You input 1'),
'2':lambda:print('You input 2'),
'3':lambda:print('You input 3')}
x = input('Input an integer to call different function:')
func = funcDict.get(x,None)
if func:
func()
else:
print('Wrong integer.')
nput an integer to call different function:5
Wrong integer.
nput an integer to call different function:2
You input 2
3.2.5 选择结构与应用
例3-1:面试资格确认。
age = 24
subject = "计算机"
college = "非重点"
if (age > 25 and subject == "电子信息工程") or \
(college == "重点" and subject == "电子信息工程") or \
(age <= 28 and subject == "计算机"):
print("恭喜,你已获得我公司的面试机会!")
else:
print("抱歉,你未达到面试要求")
恭喜,你已获得我公司的面试机会!
例3-2:用户输入若干个分数,求所有分数的平均分。每输入一个分数后询问是否继续输入下一个分数,回答“yes”就继续输入下一个分数,回答“no”就停止输入分数。
numbers = [] #使用列表存放临时数据
while True:
x = input('请输入一个成绩:')
try: #异常处理结构
numbers.append(float(x))
except:
print('不是合法成绩')
while True:
flag = input('继续输入吗?(yes/no)')
if flag.lower() not in ('yes','no'): #限定用户输入内容必须为yes或no,flag.lower()是无论输入大写还是小写,都转化为小写字符
print('只能输入yes或no')
else:
break
if flag.lower()=='no':
break
print(sum(numbers)/len(numbers))
请输入一个成绩:23
继续输入吗?(yes/no)yes
请输入一个成绩:27
继续输入吗?(yes/no)yes
请输入一个成绩:46
继续输入吗?(yes/no)yes
请输入一个成绩:4
继续输入吗?(yes/no)no
25.0
例3-2: 编写程序,判断今天是今年的第几天。
import time
data = time.localtime() #获取当前日期时间
year,month,day = data[:3]
day_month = [31,28,31,30,31,30,31,31,30,31,30,31]
if year%400==0 or (year%4==0 and year%100==0): #判断是否为闰年
day_month[1] = 29
if month == 1:
print(day)
else:
print(sum(day_month[:month-1])+day)
222
或者使用下面的方法直接计算今天是今年的第几天。
def daysBetween(year1,month1,day1,
year2,month2,day2):
from datetime import date
dif = date(year1,month1,day1)
dif = dif - date(year2,month2,day2)
return dif.days
print(daysBetween(2016,12,11,1016,11,27))
print(daysBetween(2016,12,11,1011,11,27))
365257
367084