python中的流程控制语句

python 第二课

【1】条件判断

if (1==1):
    print('1=1为真')
else:
    print('1=1为假')

1=1为真

【1.1】多重if elif else

price=10
num=5
money=40
dazhe=0.8
if money>(price*num):
    print('你有足够的钱买'+str(num)+'个单价为'+str(price)+'元的物品')
elif money>(price*num)*dazhe:
    print('打'+str(dazhe)+'折之后,你可以买得起了')
else:
    print('打'+str(dazhe)+'折之后,你还是买不起')
打0.8折之后,你还是买不起

【1.2】逻辑运算与或非 and or not

a=1
b=2
if a==b or a<b:
    print('a=b 或者 a<b')
a=b 或者 a<b

a=1
b=2
print(a and b)
2

【1.3】断言操作:assert

age=19
assert age==18,'age不等于18,抛出异常'
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-12-5263d9ebe67e> in <module>
      1 age=19
----> 2 assert age==18,'age不等于18,抛出异常'


AssertionError: age不等于18,抛出异常

【2】循环

for 循环 --遍历循环

while 循环 --条件循环

【2.1】for

costs=[3,4,11,14,15,200]
for i in costs:
    print('本次消费{}元'.format(str(i)));
本次消费3元
本次消费4元
本次消费11元
本次消费14元
本次消费15元
本次消费200元

for 中的else,如果for、while正常运行完成,则会输出else

import random
random_numbers=[]
i=1
for i in range(1,10):
    random_numbers.append(random.randint(1,10))
else:
    print('循环顺利执行完毕',random_numbers)
    
循环顺利执行完毕 [5, 1, 5, 5, 3, 10, 1, 9, 2]

【2.2】while

import random
random_numbers=[]
while len(random_numbers)<=20:
    random_numbers.append(random.randint(1,10))
print( random_numbers,len( random_numbers))
[5, 9, 7, 2, 8, 10, 1, 2, 3, 5, 8, 6, 6, 2, 8, 8, 10, 4, 3, 8, 10] 21

最佳实践:能用 for 的就不要用 while

# 使用for 循环代替 [2.2] while
random_numbers=[]
for i in range(20):
    random_numbers.append(random.randint(1,10))

print( random_numbers,len( random_numbers))
[10, 9, 7, 1, 10, 7, 7, 1, 4, 10, 2, 2, 4, 5, 3, 10, 8, 5, 4, 3] 20

什么时候必须用where循环? 当循环操作和数量没有关系的时候,只能用 while

比如当我添加随机数碰到9之后就停止循环

random_numbers=[]
while (9 not in random_numbers):
    random_numbers.append(random.randint(1,10))
print( random_numbers,len( random_numbers))
[5, 7, 1, 9] 4

【2.3】for循环可以构建推导式

所谓推导式,就是从一个数据序列构建另外一个数据序列的方法

list1=list(range(10))
list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#一般我们要构建每个值乘以10
new_list=[]
for i in list1:
    new_list.append(i*10)
print(new_list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

使用推导式构建

list1=list(range(10))
print(list1)
new_list=[ i*10 for i in list1]
print(new_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

同理,字典式推导,元组推导式

#字典推导式

list1=list(range(10))
print(list1)
dict_numbers={ i:'A' for i in list1}
print(dict_numbers)

#元组推导式

tuple1=(i*10 for i in list1)
tuple2=tuple(tuple1)
print(tuple2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
{0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A', 6: 'A', 7: 'A', 8: 'A', 9: 'A'}
(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)

利用推导式查询字典值对应的 key

dict_var1={
    'a':100,
    'b':100,
    'c':200
}

print([key for key,value in dict_var1.items() if value==100])
['a', 'b']

案例

购物车

# Auth chaoqun.guo
print("欢迎来到博马数码店~~")
while True:
    balance = input("请输入你的余额:")
    if balance.isdigit():
        break
    else:
        print("你输入的信息不规范,请输入纯整数!")
balance = int(balance)
goods_list = [
    ["Iphone", 3000],
    ["HW mate40", 4000],
    ["HW watch", 800],
    ["HW bike", 1200],
    ["MI note2", 2300]
]
shipping_list = []
while True:
    print("请选购商品(按q退出):")
    for index, goods in enumerate(goods_list):
        print(index + 1, goods)
    choice = input("请输入你要采购的商品编号:")
    if choice == 'q':
        if len(goods_list) == 0:
            print("购物车空空如也,你啥也没买!")
        else:
            print("你的余额还剩下:{},你购买了如下物品:".format(balance))
            for index, goods in enumerate(shipping_list):
                print(index + 1, goods)
        break
    elif choice.isdigit():
        choice = int(choice)
        if len(goods_list) >= choice > 0:
            if balance >= goods_list[choice - 1][1]:
                shipping_list.append(goods_list[choice - 1])
                balance = balance - goods_list[choice - 1][1]
                print("添加了物品:{} ,到你的购物车,你的余额还剩下:{}".format(goods_list[choice - 1], balance))
            else:
                print("你的钱只剩下:{},请购买其他物品或退出!".format(balance))
        else:
            print("你输入了无效的选项!")

    else:
        print("你输入了无效的选项!")

三级菜单

# 三级菜单
data = {
    '湖南省': {
        '长沙市': {
            '岳麓区': '我们这里有岳麓山啊',
            '芙蓉区': '我们这里有芙蓉广场啊'
            },
        '永州市': {
            '东安区': '我们这里有好吃的东安鸡啊',
            '祁阳县': '我们这里有好吃的炒血鸭啊'
            }
    },
        '广东省': {
            '深圳市': {
                '南山区': '我们这里有腾讯啊',
                '龙岗区': '我们这里有华为啊'
            },
            '广州市': {
                '天河区': '我说我这里有广州塔,你信吗?',
                '白云区': '我们这里有4399游戏公司,你信吗?'
            }

    }

}
exit_flag = False
while not exit_flag:
    for i in data:
        print('1', i)
    choice = input("选择进入省>>(b返回,q退出):")
    if choice in data:
        while not exit_flag:
            for i2 in data[choice]:
                print("\t2.",i2)
            choice2 = input("选择进入市>>(b返回,q退出):")
            if choice2 in data[choice]:
                while not exit_flag:
                    for i3 in data[choice][choice2]:
                        print("\t\t3.", i3)
                    choice3 = input("选择进入区(b返回,q退出)>>:")
                    if choice3 in data[choice][choice2]:
                        print(data[choice][choice2][choice3])
                    elif choice3 == 'b':
                        break
                    elif choice3 == 'q':
                        exit_flag = True
                    else:
                        print("您输入的名称不存在,请查看列表重新输入~~")

            elif choice2 == 'b':
                break
            elif choice2 == 'q':
                exit_flag = True
            else:
                print("您输入的名称不存在,请查看列表重新输入~~")
    elif choice == 'b':
        break
    elif choice == 'q':
        exit_flag = True
    else:
        print("您输入的名称不存在,请查看列表重新输入~~")

posted @ 2020-07-08 20:17  郭大侠1  阅读(163)  评论(0编辑  收藏  举报