循环进阶
多层多次跳出
break_flag = False
for i in range(10):
print('爷爷层',i)
for j in range(10):
print('爸爸层',j)
for k in range(10):
print('孙子层',k)
if k == 2:
break_flag = True
break
if break_flag:
break
if break_flag:
break
print('正常退出循环')
多层一次跳出
break_flag = False
while break_flag == False :
print('爷爷')
while break_flag == False :
print('爸爸')
while break_flag == False :
print('孙子')
break_flag = True
break
else :
print('完了')
购物车
product_list = [['Iphone7',5800],
['Coffee',30],
['疙瘩汤',10],
['Python Book',99],
['Bike',199],
['ViVo X9',2499], ]
shopping_cart = {}
salary = int(input("input your salary:"))
while True :
index = 0
for product in product_list:
print(index,product)
index += 1
choice = input('>> :').strip()
if choice.isdigit():
choice = int(choice)
if choice >= 0 and choice < len(product_list):
product = product_list[choice]
if product[1] <= salary:
if product[0] in shopping_cart :
shopping_cart[product[0]][1] +=1 #如果商品本身存在在购物车里,则字典中的商品数量加一
else:
shopping_cart[product[0]] = [product[1],1]#如果商品没在购物车中,则字典中加入一个商品元素
salary -= product[1]
print('added product'+' '+ product[0] + ' '+'into shopping cart' ,
'your current balance is ' +str(salary))
else :
print('买不起,穷逼! 产品价格是' + str(product[1]) + '你还差' + str(product[1]-salary) + '元')
else :
print('商品不存在')
elif choice == 'q':
print('--------已购买商品列表--------')
id_count = 1
total = 0 # 初始化一个总花费的变量
print('id 商品 数量 单价 总价')
for key in shopping_cart:
print('%s %s %s %s %s'%(id_count,
key,
shopping_cart[key][1],
shopping_cart[key][0],
shopping_cart[key][1]*shopping_cart[key][0]))
id_count += 1
total += shopping_cart[key][1]*shopping_cart[key][0]
print('您的总花费为:',total)
print('您的余额为:',salary)
print('------------end---------------')
break
else:
print('无此选项')
三级菜单
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
}
last_layer = [ menu ]
current_layer = menu
while True:
for key in current_layer:
print(key)
choice = input('>> :').strip()
if len(choice) == 0 : continue
if choice in current_layer:
last_layer.append(current_layer)
current_layer = current_layer[choice]
if choice == 'b':
current_layer = last_layer[-1]
last_layer.pop()
if choice == 'q':
break