跳出多层循环:三层循环,最里层直接跳出3层
在Python中,函数运行到return这一句就会停止,因此可以利用这一特性,将功能写成函数,终止多重循环
def work(): for i in range(5): print("i=", i) for j in range(5): print("--j=", j) for k in range(5): if k<2: print("------>k=", k) else: return i,j,k print (work())
注:后面对此进行更新拓展,链接如下:
http://www.cnblogs.com/xuyaping/p/6639830.html
购物车程序
需求:1.启动程序后,让用户输入工资,然后打印商品列表
2.允许用户根据商品编号购买商品
3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4.可随时退出,退出时,打印已购买商品和余额
salary=int(input("input your salary:")) #输入工资 balance=salary #将工资赋值给余额 products=["book","coffe","cake","iphone"] #定义可购买商品 price=[40,20,30,2000] #定义商品价格 print("number ","products ","price") #输出商品列表第一行 products_buy=[] #设置购物车商品列表 for i in range(len(products)): #输出商品列表产品及价格 print(i+1," ",products[i]," ", price[i]) print("q"," ","quit") #输出“q”指令打印命令“quit”(退出) while True: number = input("input your products_number:") if number!="q": #若输入的不是“q”,则为整型,循环打印已购买商品和余额 number_=int(number) if balance >=price[number_-1]: balance -= price[number_ - 1] products_buy.append(products[number_-1]) print("products_buy is",products_buy,",balance is ",balance) else: print("余额不足!") else: #输入的为“q”,打印已购买商品和余额 print("products_buy is", products_buy, ",balance is ", balance) break
运行程序:
注:后面对此进行更新拓展,链接如下:
http://www.cnblogs.com/xuyaping/p/6639850.html