day7.条件和循环

一.if语句

  单分支,单重条件判断

    if expression:
        expr_true_suite
 
  单分支,多重条件判断
    if not  active or over_time >= 10:
        print('Warning:service is dead')
        warn_tag+=1
 
  if+else
    if expression:
        expr_true_suite
    else:
        expr_false_suite
 
  多分支if+elif+else
    if expession1:
        expr1_true_suite
    elif expression2:
        expr2_true_suite
    elif expession3:
        expr3_true_suite
    else:
        none_of_the_above_suite
 

  三元表达式

    语法:

    expr_true_suite if expession else expr_false_suite

    案例一:

>>> active=1
>>> print('service is active') if active else print('service is inactive')
service is active

    案例二:

>>> x=1
>>> y=2
>>> smaller=x if x < y else y
>>> smaller
1

二.while语句

  

2.2.1:基本语法

while expression:

    suite_to_repeat

注解:重复执行suite_to_repeat,直到expression不再为真

2.2.2:计数循环

count=0
while (count < 9):
    print('the loop is %s' %count)
    count+=1 

2.2.3:无限循环

count=0
while True:
    print('the loop is %s' %count)
    count+=1

tag=True
count=0
while tag:
    if count == 9:
        tag=False
    print('the loop is %s' %count)
    count+=1 
跳出无限循环

2.2.4:while与break,continue,else连用

count=0
while (count < 9):
    count+=1
    if count == 3:
        print('跳出本层循环,即彻底终结这一个/层while循环')
        break
    print('the loop is %s' %count)
break跳出本层循环
count=0
while (count < 9):
    count+=1
    if count == 3:
        print('跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环')
        continue
    print('the loop is %s' %count)
continue跳出本次循环
count=0
while (count < 9):
    count+=1
    if count == 3:
        print('跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环')
        continue
    print('the loop is %s' %count)
else:
    print('循环不被break打断,即正常结束,就会执行else后代码块')




count=0
while (count < 9):
    count+=1
    if count == 3:
        print('跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环')
        break
    print('the loop is %s' %count)
else:
    print('循环被break打断,即非正常结束,就不会执行else后代码块')
循环被break打断,即非正常结束,就不会执行else后代码块

2.2.5:while语句小结

  • 条件为真就重复执行代码,直到条件不再为真,而if是条件为真,只执行一次代码就结束了
  • while有计数循环和无限循环两种,无限循环可以用于某一服务的主程序一直处于等待被连接的状态
  • break代表跳出本层循环,continue代表跳出本次循环
  • while循环在没有被break打断的情况下结束,会执行else后代码

三.for语句

3.1 功能

  for 循环提供了python中最强大的循环结构

  (for循环是一种迭代循环机制,而while循环是条件循环,迭代即重复相同的逻辑操作,每次操作都是基于上一次的结果,而进行的)

3.2 语法

  3.2.1:基本语法

    for iter_var in iterable:

        suite_to_repeat

    注解:每次循环, iter_var 迭代变量被设置为可迭代对象(序列, 迭代器, 或者是其他支持迭代的对 象)的当前元素, 提供给 suite_to_repeat 语句块使用.

  3.2.2:遍历序列类型

name_list=['alex','eric','rain','xxx']

#通过序列项迭代
for i in name_list:
    print(i)

#通过序列索引迭代
for i in range(len(name_list)):
    print('index is %s,name is %s' %(i,name_list[i]))

#基于enumerate的项和索引
for i,name in enumerate(name_list,2):
    print('index is %s,name is %s' %(i,name)) 

  3.2.3:遍历可迭代对象或迭代器

    迭代对象:就是一个具有next()方法的对象,obj.next()每执行一次,返回一行内容

    所有内容迭代完后,迭代器引发一 个 StopIteration 异常告诉程序循环结束.

    for 语句在内部调用 next() 并捕获异常.

    for循环遍历迭代器或可迭代对象与遍历序列的方法并无二致,只是在内部做了调用迭代器next(),并捕获异常,终止循环的操作

    很多时候你根本无法区分for循环的是序列对象还是迭代器 

>>> f=open('a.txt','r')

for i in f:
    print(i.strip())
hello
everyone
sb

  3.2.4:for基于range()实现计数循环  

  range()语法:

    range(start,end,step=1):顾头不顾尾

  •   range(10):默认step=1,start=0,生成可迭代对象,包含[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  •   range(1,10):指定start=1,end=10,默认step=1,生成可迭代对象,包含[1, 2, 3, 4, 5, 6, 7, 8, 9]
  •   range(1,10,2):指定start=1,end=10,step=2,生成可迭代对象,包含[1, 3, 5, 7, 9]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9

  注:for基于range()实现计数循环,range()生成可迭代对象,说明for循环本质还是一种迭代循环

  

3.2.5:for与break,continue,else

  同while

3.2.6:for语句小结

  • for循环为迭代循环
  • 可遍历序列成员(字符串,列表,元组)
  • 可遍历任何可迭代对象(字典,文件等)
  • 可以用在列表解析和生成器表达式中
  • break,continue,else在for中用法与while中一致

3.3 案例

albums = ('Poe', 'Gaudi', 'Freud', 'Poe2')
years = (1976, 1987, 1990, 2003)

#sorted:排序
for album in sorted(albums):
    print(album)

#reversed:翻转
for album in reversed(albums):
    print(album)

#enumerate:返回项和
for i in enumerate(albums):
    print(i)
#zip:组合
for i in zip(albums,years):
    print(i)

四.练习

一、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 
三、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
 
四、购物车
功能要求:

要求用户输入总资产,例如:2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
附加:可充值、某商品移除购物车
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
 五、用户交互,显示省市县三级联动的选择

dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    }
    "河南": {
        ...
    }
    "山西": {
        ...
    }
 
}
原文地址:https://www.cnblogs.com/maxiaotiaoshishui/p/7207418.html