標籤:python for迴圈 購物車 小程式 列表
for迴圈
for 變數 in 範圍: 代碼塊... contune #跳出本次迴圈接著執行下一次迴圈 for 變數 in 範圍: 代碼塊... break #跳出本層迴圈,回到上一個for迴圈else: #其實for迴圈和while迴圈都有else子句,不過是當迴圈完全執行了才會執行 代碼塊... 其他主程式碼塊...
#作業1--跳出三層for迴圈
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) break else: continue break else: continue‘‘‘作業2-購物車程式顧客可以根據自己的工資購買想要的東西,每次購買完成會計算剩餘的金額‘‘‘
print("----------Welcome to oldboy market----------")print("------Today You can buy all of these:-------")print("--Iphone<>Computer<>Coffee<>Book<>Clothes--")shopping_car = []client_salary = int(input("Please input your salary:"))while True: items = [[‘Iphone‘, 5000], [‘Computer‘, 7999], [‘Coffee‘, 30], [‘Book‘, 80], [‘Clother‘, 600]] i = 1 enable_list = [] # 使用者能購買的東西 disable_list = [] # 使用者不能買的東西 cost_list = [] # 能購買的商品價格 name_list = [] # 能購買的商品名字 print("You can buy these:\n") for item in items: if item[1] <= client_salary: enable_list.append(item) cost_list.append(item[1]) name_list.append(item[0]) print(i, item[0], " ", item[1]) i += 1 else: disable_list.append(item) continue print("Q quit shopping") print("------------------------------------------------------") print("You can not buy these,because you don‘t have enough money!\n", disable_list) print("------------------------------------------------------") choice = input("what‘s your choice number or quit:") if choice == ‘q‘ or choice == ‘Q‘: print("Today you have buy these :",shopping_car) break else: choice = int(choice)-1 if choice <= len(enable_list): if cost_list[choice] <= client_salary: shopping_car.append(enable_list[choice]) #將選擇的商品加到購物車 client_salary = client_salary - cost_list[choice] print("The " ,enable_list[choice] , " is added to the shoppingcart \nyour balance is ",client_salary) print("------------------------------------------------------") print("Have Buy:",shopping_car) print("------------------------------------------------------") else: print("You don‘t have enough money to buy this!") continue else: print("Your choice is wrong,Please try again!") continue
python迴圈之for迴圈與類比購物車小程式