zoukankan      html  css  js  c++  java
  • for and while 循环语句

    for and while 循环语句

    返回首页

    for 循环语法:for i in range()

      在for循环的语法中,“i”是每次循环出来的参数,是一个临时的变量,range()是要循环的次数范围。range()也可以是其他的数据形式,只要可以被循环就行,做常见的是列表。

      注意:break 是跳出本层循环、continue 是跳出本次循环。

      for循环中,用break跳出本层循环:

    # # 用break跳出多层for循环
    for i in range(10):
        print("i",i)
        if i >5:
            for j in range(10):
                if j == 3:
                    break
                print("-----j",j)
            print("break跳出本层循环")

      for循环中,用continue跳出本次循环:

    # # 用 continue 跳出本层循环
    for i in range(10):
        if i >= 5:
            print(i)
        else:
            continue  # 跳出本次循环
            # print("-=----",i)
    for i in range(10):
        print("i",i)
        if i >5:
            for j in range(10):
                if j == 3:
                    continue
                print("-----j",j)
            print("continue跳出本次循环")

      for循环语法中,也可以有else:当for循环正常结束,执行else。

    # # for循环里的else
    for i in range(10):
        print(i)
        if i== 5:
            break
    else: #当循环正常结束时,走else
        print("done")
    print("done2")

    while 循环语法:while 1 or while True,只要条件满足,while会一直循环下去的。

      在while循环语句中,他的判定条件是1或True。并且循环不像for一样有循环范围,while是一直循环下去。

    count = 0
    while True:
        print("宝贝儿,叫爸爸...",count)
        count +=1

      终止while循环的方法:该其条件True或1,或使其break。

      用break:

    count = 0
    while True:
        print("宝贝儿,叫爸爸...",count)
        count +=1
        if count == 10:
            print("宝贝儿,叫爸爸...",count)
            break

      改变while的条件:

    count = 0
    while count <10:
        print("宝贝儿,叫爸爸...",count)
        count +=1
    count = 0
    while True:
        print("宝贝儿,叫爸爸...",count)
        count +=1
        if count == 50:
            print("宝贝儿,叫爸爸...",count)
            break

      while也有else语句:在while正常结束是执行else,如果while是break终止的,那么else不执行。

      执行else:

    count = 0
    while count <10:
        print("宝贝儿,叫爸爸...",count)
        count +=1
    else:
        print("done....")

      不执行else:

    count = 0
    while count <10:
        print("宝贝儿,叫爸爸...",count)
        count +=1
        if count == 5:
            break
    else:
        print("done....")

    ### 作业 ###

    # 跳出多层循环(三层循环),从最里层跳出

      while循环三层跳出:

    break_flag = False
    count = 0
    
    while break_flag == False:
        print('-第一层-')
        while break_flag == False:
            print('==第二层==')
            while break_flag == False:
                count +=1
                if count >2:
                    break_flag = True
                print('+++第三层+++',count)
    print('出来了')

      for循环三层跳出:

    break_flag = False
    for i in range(10):
        print("-第一层-",i)
        for j in range(10):
            print('==第二层==',j)
            if j==3:
                break_flag = True
                break
            for k in range(10):
                print('+++第三层+++',k)
                if k == 6:
                    break_flag = True
                    print("k等于",k,", 第三层出来了")
                    break
            if break_flag:
                break
        if break_flag:
            print("j等于",j,", 第二层出来了")
            break
    print('出来了')

    # while 猜年龄

    my_number = 26
    count = 0
    while count<3:
        user_input = int(input("input your number:"))
        if user_input == my_number:
            print("you got it")
            break
        elif user_input < my_number:
            print("min")
        else:
            print('max')
        count +=1  # 每次loop,计数器count加1
    else:
        print('傻狗')

    # 购物车shopping

    ## 1.0 Beta

    shopping_list = [
        ["iphone",11000],
        ["MacBook Pro",32000],
        ["iPad Pro",8000],
        ["Apple Pencil",1000],
        ["Magic keyboard",600],
        ["Coffee",42]
    ]
    shopping_cart = []
    Your_salary = int(input("input your salary:"))
    
    while True:
        index = 0
        for shopping in shopping_list:
            print(index,shopping)
            index += 1
        choice_shopping = input(">>:").strip()
        #判断是否为数字
        if choice_shopping.isdigit():
            choice_shopping = int(choice_shopping)
            #商品存在
            if choice_shopping >=0 and choice_shopping <len(shopping_list):
                #取到商品
                shopping = shopping_list[choice_shopping]
                #判断薪资和商品价格
                if shopping[1] <= Your_salary:
                    #买得起,加入购物车
                    shopping_cart.append(shopping)
                    #薪资减商品价格
                    Your_salary -= shopping[1]
                    # print("购物车:",shopping_cart,"余额:",Your_salary)
                    print("Added shopping " + shopping[0] + " into shopping cart,33[42;1myour current33[0m balance " + str(Your_salary))
                else:
                    print("资金不足,商品价格" + str(shopping[1]) + "Your have need: " + str(shopping[1]-Your_salary) + "")
            else:
                print("商品不存在!!!")
        elif choice_shopping == "Q" or "q":
            print("--- 购物车 ---")
            for i in shopping_cart:
                print(i)
            print("余额: ",Your_salary)
            print("--- END ---")
            break
        else:
            print("无此选项!!!")

    ## 1.1.0 Beta

    #修复项:1、在显示时,提示Q或q可退出程序。

           2、在商品的显示列表中,显示商品的id号。

          3、格式化输出已购买商品的id、商品名、数量、单价、总价、合计总价。

    product_list = [
        ["iphone Pro",11000],
        ["MacBook Pro",32000],
        ["iPad Pro",8000],
        ["Apple Pencil",1000],
        ["Magic Keyboard",600],
        ["Coffee",42]
    ]
    shopping_cart = {}
    Your_salary = int(input("input your salary:"))
    
    while True:
        index = 0
        for product in product_list:
            print(index,product)
            index += 1
        choice_product = input(">>:").strip()
        if choice_product.isdigit():   #判断是否为数字
            choice_product = int(choice_product)
            if choice_product >=0 and choice_product <len(product_list): #商品存在
                product = product_list[choice_product]   #取到商品
                if product[1] <= Your_salary:   #判断薪资和商品价格
                    if product[0] in shopping_cart: #之前买过
                        shopping_cart[product[0]][1] += 1 # 购物车已有该商品,该商品数量加一
                    else:
                        shopping_cart[product[0]] = [product[1], 1]   #创建一条新的商品购买记录
                    Your_salary -= product[1]   #薪资减商品价格
                    print("Added shopping " + product[0] + " into shopping cart,33[42;1myour current33[0m balance " + str(Your_salary))
                    # print("购物车:",shopping_cart,"余额:",Your_salary)
                else:
                    print("资金不足,商品价格" + str(product[1]) + "Your have need: " + str(product[1]-Your_salary) + "")
            else:
                print("!商品不存在 !")
        elif choice_product == "Q" or "q":
            print("--- 已购买商品列表 ---")
            print(shopping_cart)
            id_counter = 1
            total_cost = 0 #初始化一个总花费的变量
            print(" id   商品   数量   单价   总价 ")
            for key in shopping_cart:
                print("%s	%s	%s	%s	%s" %(id_counter,
                      key,
                      shopping_cart[key][1],
                      shopping_cart[key][0],
                      shopping_cart[key][1]*shopping_cart[key][0]))
                id_counter +=1
                total_cost += shopping_cart[key][1]*shopping_cart[key][0] #单个商品总价
            print("总花费: ",total_cost)
            print("余额: ",Your_salary)
            print("--- END ---")
            break
        else:
            print("无此选项!!!")

        

    #三级菜单

    menu = {
        '北京':{
            '海淀':{
                '五道口':{
                    'soho':{},
                    '网易':{},
                    'google':{}
                },
                '中关村':{
                    '爱奇艺':{},
                    '汽车之家':{},
                    'youku':{},
                },
                '上地':{
                    '百度':{},
                },
            },
            '昌平':{
                '沙河':{
                    '老男孩':{},
                    '北航':{},
                },
                '天通苑':{},
                '回龙观':{},
            },
            '朝阳':{},
            '东城':{},
        },
        '上海':{
            '闵行':{
                "人民广场":{
                    '炸鸡店':{}
                }
            },
            '闸北':{
                '火车战':{
                    '携程':{}
                }
            },
            '浦东':{},
        },
        '山东':{},
    }
    menu
    exit_flag = False
    while not exit_flag:
        for key in menu:
            print(key)
    
        choice = input(">:").strip()
        if len(choice) == 0 : continue
        if choice == 'q':
            exit_flag = True
            continue
        if choice in menu: #省存在,进入此省下一级
            while not exit_flag:
                next_layer = menu[choice]
                for key2 in next_layer:
                    print(key2)
                choice2 = input(">>:").strip()
                if len(choice2) == 0: continue
                if choice2 == 'b': break
                if choice2 == 'q':
                    exit_flag = True
                    continue
                if choice2 in next_layer: #再进入下一层
                    while not exit_flag:
                        next_layer2 = next_layer[choice2]
                        for key3 in next_layer2:
                            print(key3)
                        choice3 = input(">>>:").strip()
                        if len(choice3) == 0: continue
                        if choice3 == 'b': break
                        if choice3 == 'q':
                            exit_flag = True
                            continue
    
                        if choice3 in next_layer2:
                            while not exit_flag:
                                next_layer3 = next_layer2[choice3]
                                for key4 in next_layer3:
                                    print(key4)
    
                                choice4 = input(">>>>:").strip()
                                if choice4 == 'b':break
                                if choice4 == 'q':
                                    exit_flag = True
                                    continue

     ## 三级菜单 1.1.0 Beta

     ### 修复内容:1、简化代码复用性。

            2、修复返回操作时,到最初菜单就退出程序的Bug。

    #定义一个初始化层级,当前层
    current_layer = menu   #当前层
    last_layers = [menu]   #上一层
    
    while True:
        for key in current_layer:
            print(key)
        print("输入'b'返回上一层,输入'q'退出程序。")
    
        choice = input('>>:').strip()
        if len(choice) == 0:
            continue
        if choice in current_layer:    #进入下一层级
            last_layers.append(current_layer)   # 取当前层,添加到列表
            current_layer = current_layer[choice]    #当起层
        if choice == 'b':
            if last_layers:  #判断上一层是否有值,没有值就不在退了
                current_layer = last_layers[-1]   #取上一层,赋值给current_layer
                last_layers.pop()
                print("以返回上一层")
        if choice == 'q':
            print('退出程序')
            break

    ---------- END ----------

  • 相关阅读:
    struts2学习笔记(二)
    struts2学习问题(一)
    struts2学习(一)
    给 ecplise 配置struts2配置环境
    Servlet的生命周期
    奇数位丢弃
    快速排序和归并排序(C语言)
    学习正则表达式及c#应用
    C#string与stringBuilder的区别
    c#之字符串函数
  • 原文地址:https://www.cnblogs.com/george92/p/12644123.html
Copyright © 2011-2022 走看看