流程控制¶
if¶
if,条件判断,当满足不同的条件的时候执行不同的操作
if <条件一>:
<条件一代码块>
elif <条件二>:
<条件二代码块>
else:
<上面两个或者多个条件都不满足则运行这里的代码块>
举个🌰
➜ python_test cat if.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# 提示用户输入一个数字,并将其赋值给变量n
n = int(input("Num: "))
if n > 10:
print("n > 10")
elif n == 10:
print("n = 10")
else:
print("n < 10")
三元运算¶
var = 值1 if 条件 else 值2
如果条件成立,把值1赋值给var,如果条件不成立,把值2赋值给var
>>> var = "True" if 1==1 else "False"
>>> var
'True'
for循环¶
循环控制语句,可用来遍历某一对象,还具有一个附带的可选的else块,主要用于处理for循环中包含的break语句
IndentationError: expected an indented block
>>> li = ['yang', 'jie']
>>> for n in range(len(li)):
... print(li[n])
...
yang
jie
enumerate¶
enumerate
函数用于遍历序列中的元素以及它们的下标
>>> li = ["computer", "note", "phone", "lalala"]
>>> for key,value in enumerate(li):
... print(key, value)
...
0 computer
1 note
2 phone
3 lalala
为了给用户良好的体验,需要从1开始,然后用户如果输出相对应的序列,那么就打印出序列对应的值
➜ python_test cat 008-1.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
li = ["computer","note","phone","lalala"]
# enumerate默认从0开始自增,可以改为从1开始自增
for key,value in enumerate(li,1):
print(key,value)
# 让用户选择商品的序列
li_num=input("请选择: ")
# print输出的时候让序列减1
print(li[int(li_num)-1])
执行效果如下
➜ python_test python3 008-1.py
1 computer
2 note
3 phone
4 lalala
请选择: 2
note
range和xrange¶
range()函数返回在特定区间的数字序列,range()函数的用法类似切片:range(start,stop,step),start的默认值为0,即从0开始,stop的参数是必须输入的,输出的最后一个数值是stop的前一个,step的默认值是1,即步长为1
>>> for n in range(5):
... print(n)
...
0
1
2
3
4
反向输出
>>> for n in range(5,-1,-1):
... print(n)
...
5
4
3
2
1
0
range在python2.7与3.5的差别
range在python2.7中,会把所有的序列都输出出来,每一个序列都在内存中占用空间
➜ ~ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> range(1,100)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>>
xrange不会一次性把序列全部都存放在内存中,而是用到for循环进行迭代的时候才会一个一个的存到内存中,相当于python3.5中的range
>>> for i in xrange(10):
... print(i)
...
0
1
2
3
4
5
6
7
8
9
➜ ~ python3
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 08:49:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> range(1,100)
range(1, 100)
range在python3.5中不会一次性的占用那么多空间,它会在我们需要用到的时候再在内存中开辟一块空间给这个序列,不是一次性分配完,相当于python2.7中的xrange
while¶
while
循环不同于for
循环,while
循环是只要条件满足,那么就会一直运行代码块,否则就运行else
条件一代码块
while <条件>:
<代码块>
else:
<如果条件不成立执行这里的代码块>
举个🌰
➜ python_test cat 008-2-while.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
flag = True
while flag:
print(flag)
flag = False
else:
print('else',flag)
➜ python_test python3 008-2-while.py
True
else False
练习¶
元素分类¶
有如下值集合[11,22,33,44,55,66,77,88,99,90],将所有大于66的值保存至字典的第一个key中,将小于66的值保存至第二个key的值中
即: {'k1':大于66的所有值,'k2':小于66的所有值}
➜ python_test cat 008-3-exercise-1.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
num = [11,22,33,44,55,66,77,88,99,90]
dict = {
'k1':[],
'k2':[]
}
for n in range(len(num)):
if num[n] <= 66:
dict['k1'].append(num[n])
else:
dict['k2'].append(num[n])
print(dict.get("k1"))
print(dict.get("k2"))
➜ python_test python3 008-3-exercise-1.py
[11, 22, 33, 44, 55, 66]
[77, 88, 99, 90]
查找¶
查找列表中元素,移动空格,并查找以a或A开头,并且以c结尾的所有元素
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
列表的方式
➜ python_test cat 008-3-exercise-2.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
li = ["alec", " aric", "Alex", "Tony", "rain"]
for n in range(len(li)):
string = str(li[n]).replace(" ","").capitalize()
# 去掉左右两边的空格然后输出内容并且把首字母换成大写
# string = str(li[n]).strip().capitalize()
# 把字符串中的空格替换掉,然后首字母转换成大写
if string.find("A") == 0 and string.rfind("c") == len(string) - 1:
print(li[n],"--->",string)
➜ python_test python3 008-3-exercise-2.py
alec ---> Alec
aric ---> Aric
元组的方式
➜ python_test cat 008-3-exercise-3.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
tu = ("alec", " aric", "Alex", "Tony", "rain")
for n in range(len(tu)):
string = str(tu[n]).replace(" ","").capitalize()
if string.find("A") == 0 and string.rfind("c") == len(string) - 1:
print(tu[n],"--->",string)
字典的方式
➜ python_test cat 008-3-exercise-4.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
dic = {
'k1': "alex",
'k2': ' aric',
"k3": "Alex",
"k4": "Tony"
}
for key,val in dic.items():
string = str(val).replace(" ","").capitalize()
if string.find("A") == 0 and string.rfind("c") == len(string) - 1:
print(key,val,"--->",string)
➜ python_test python3 008-3-exercise-4.py
k2 aric ---> Aric
输出商品列表¶
用户输入序号,显示用户选中的商品
商品
li = ["phone","computer","fish","wahaha"]
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
li = ["phone","computer","fish","wahaha"]
for key,value in enumerate(li,1):
print(key,".",value)
li_num = input ("please input your choice: ")
print(li[int(li_num)-1])
执行结果
➜ python_test python3 008-3-exercise-5.py
1 . phone
2 . computer
3 . fish
4 . wahaha
please input your choice: 1
phone
购物车¶
功能要求
要求用户输入总资产,例如:2000 显示商品列表,让用户根据序号选择商品,加入购物车 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功 附加:可充值,某商品移除购物车
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
switch = "on"
gouwuche = {
"wuping":[],
"jiage":[]
}
# 用户输入卡内余额
while True:
try:
money = int(input("请输入卡内余额:"))
# 异常判断,如果类型不是整型则执行except内的代码
except ValueError:
# 提示用户输入的格式错误,让其重新输入
print("error,余额格式输入错误,请重新输入!\n例如: 5000")
# 中断当前循环让 循环重新执行
continue
break
# 进入购买商品的流程
while switch == "on":
# 打印出所有的商品
print("\n","序列","商品","单价")
# 以序列的方式输出现拥有的商品及商品单价
for num,val in enumerate(goods,1):
for n in range(len(goods)):
if num-1 == n:
print(" ",num,goods[n]["name"],goods[n]["price"])
# 判断用户输入的序列是否规范
while True:
try:
# 输入产品序列,类型转换为整型
x = int(input("请选择商品序列: "))
# 如果用户输入的非整型,提示用户重新输入
except ValueError:
print("error,请选择商品序列")
continue
# 如果用户输入的序列不在产品序列当中让用户重新输入
if x > num:
print("error,请选择商品的序列")
continue
break
# 输出购买物品的信息
print("您已经把商品",goods[x-1]["name"],"加入购物车","物品单价是: ",goods[x-1]["price"],"\n")
# 把物品名称放入gouwuche的wuping列表中
gouwuche["wuping"].append(goods[x-1]["name"])
# 把物品单价放入gouwuche的jiage列表中
gouwuche["jiage"].append(goods[x-1]["price"])
# 用户输入选项
while switch == "on":
# 输出现有选项
print("================\n查看购物车: p\n结算: w \n删除商品: d \n继续购买: n \n充值: i \n显示余额: m \n退出: q")
# 把用户输入的选项转换为字符串
xx = str(input("请输入您的选择: "))
if xx == "p":
for wp_num,val in enumerate(gouwuche["wuping"],1):
print(wp_num,val)
elif xx == "w":
zje = 0
for n in range(len(gouwuche["jiage"])):
zje += gouwuche["jiage"][n]
if zje > money:
print("sorry , 钱不够哦~~ \n")
else:
switch = "off"
print("购物愉快,您本次消费",zje,"RMB","剩余",money-zje,"RMB")
elif xx == "d":
for wu_num,val in enumerate(gouwuche["wuping"],1):
print(wp_num,val)
while True:
try:
delete = int(input("请选择要删除的商品序列: "))
except ValueError:
print("error,请输如正确的序列号!")
continue
if delete > wp_num:
print("error,请输如正确的序列号!")
continue
# 提示用户购物车内被删除的商品信息
print("您已经删除产品",gouwuche["wuping"],[delete - 1],"单价为: ",gouwuche["jiage"][delete - 1])
# 删除商品
gouwuche["wuping"].pop(delete - 1)
# 删除金额
gouwuche["jiage"].pop(delete - 1)
break
elif xx == "i":
while True:
try:
user = int(input("请输入您的账号: "))
except ValueError:
print("error,账号格式输入错误,请重新输入..")
continue
break
while True:
try:
pwd = int(input("请输入账号密码: "))
except ValueError:
print("error,格式错误,请重新输入...")
continue
break
if user == 123 and pwd == 123:
while True:
try:
newmoney = int(input("请输入充值的金额: "))
except ValueError:
print("error,金额格式错误,请重新输入..")
continue
break
money += newmoney
print("您已充值成功",newmoney,"RMB, 当前余额为: ",money," RMB \n")
else:
print("账号或密码错误\n")
elif xx == "m":
print("账户余额: ",money,"\n")
elif xx == "q":
switch = "off"
elif xx == "n":
break
else:
print("请输入正确的选项! ")
三级联动¶
用户交互,显示省市县的选择
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
area = {
"湖北": {
"武汉":["汉口","武昌","汉阳"],
"咸宁":["崇阳","通城","白霓"]
},
"河南": {
"郑州市":["中原区","二七区","金水区"],
"洛阳市":["涧西区","西工区","老城区"]
},
"湖南": {
"长沙":["芙蓉区","岳麓区"],
"岳阳":["hello","哈哈"]
}
}
switch = "on"
print("\n====China====\n")
while switch == "on":
sheng = []
shi = []
zhen = []
while switch == "on":
for sheng_n,sheng_v in enumerate(area,1):
print(sheng_n,sheng_v)
sheng.append(sheng_v)
try:
sheng_inp = int(input("please input sheng: "))
except ValueError:
print("input error")
continue
if sheng_inp > sheng_n or sheng_inp == 0:
print("input error")
continue
print("\nChina --->",sheng[sheng_inp - 1],"\n")
break
while True:
ify = input("b back\nn continue\nq quit\n please input your choice: ")
if ify == "q" or ify == "b" or ify == "n":
break
else:
print("input error")
continue
if ify == "b":
continue
elif ify == "q":
switch = "off"
continue
while switch == "on":
for shi_n,shi_v in enumerate(area[sheng[sheng_inp - 1]],1):
print(shi_n,shi_v)
shi.append(shi_v)
try:
shi_inp = int(input("please input your choice "))
except ValueError:
print("input error")
continue
if shi_n < shi_inp or shi_inp == 0:
print("input error")
continue
print("\n China --->",sheng[sheng_inp - 1],"--->",shi[shi_inp - 1])
while True:
ify = input("b back\nn continue\nq quit\n please input your choice: ")
if ify == "q" or ify == "b" or ify == "n":
break
else:
print("input error")
continue
if ify == "b":
continue
elif ify == "q":
switch = "off"
continue
while switch == "on":
for zhen_n,zhen_v in enumerate(area[sheng[sheng_inp - 1]][shi[shi_inp - 1]],1):
print(zhen_n,zhen_v)
zhen.append(zhen_v)
try:
zhen_inp = int(input("please input your choice: "))
except ValueError:
print("input error")
continue
if zhen_n < zhen_inp or zhen_inp == 0:
print("input error")
continue
print("\n China --->",sheng[sheng_inp - 1],"--->",shi[shi_inp - 1],"--->",zhen[zhen_inp - 1])
while True:
ify = input("b back\nq quit\n please input your choice: ")
if ify == "q" or ify == "b":
break
else:
print("input error")
continue
if ify == "b":
continue
elif ify == "q":
switch = "off"
continue
执行结果
➜ python_test python3 008-3-exercise-sanjiliandong.py
====China====
1 湖北
2 河南
3 湖南
please input sheng: 1
China ---> 湖北
b back
n continue
q quit
please input your choice: n
1 武汉
2 咸宁
please input your choice 1
China ---> 湖北 ---> 武汉
b back
n continue
q quit
please input your choice: n
1 汉口
2 武昌
3 汉阳
please input your choice: 1
China ---> 湖北 ---> 武汉 ---> 汉口
b back
q quit
please input your choice: q