• 表达式for loop


    最简单的循环10次

    #-*- coding: utf-8 -*-
    #Author = "zero"
    
    for i in range(10):
           print("loop:",i)
    View Code

    输出:

    loop: 0
    loop: 1
    loop: 2
    loop: 3
    loop: 4
    loop: 5
    loop: 6
    loop: 7
    loop: 8
    loop: 9
    View Code

    需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环

    for i in range(10):
        if i<5:
            continue #不往下走了,直接进入下一次loop
        print("loop:", i )
    View Code

    需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出

    for i in range(10):
        if i>5:
            break #不往下走了,直接跳出整个loop
        print("loop:", i )
    View Code

    需求三:还是上面的程序,但是每跳一个打印一个,打印完毕退出

    for i in range(0,10,2):
           print("loop ",i)
    View Code

     加断点测试continue用法

    for i in range(0,10):
         if i < 3:
               print("loop ",i)
         else:
               continue
          print("hehe......")
    View Code

    两个for循环

    for i in range(10):
         print("-------------",i)
         for j in range(10):
         print(j)
    View Code
    for i in range(10):
         print("-------------",i)
         for j in range(10):
         print(j)
         if j>5:
              break
    View Code

    总结:continue跳出本次循环,进入下一次循环,break结束当前当次整个循环。

    用for代替刚刚的猜年龄程序:

    age_of_oldboy = 28
    
    for i in range(3):
    
           guess_age == int(input("guess age:"))
           if guess_age == age_of_oldboy:
                 print("yes, you got it.")
                 break
           elif guess_age < age_of_oldboy:
                 print("think bigger!")
           else:
                 print("think smaller......")
    else:
           print("you have tried too many times..funck off!!")
    View Code

     还是猜年龄程序,要求每猜错三次提示“还要不要继续玩?”

    age_of_oldboy = 28
    
    count = 0
    while count < 3:
            guess_age = in(input("guess age:"))
            if guess_age == age_of_oldboy :
                  print("yes, you got it.")
                  break
             elif guess_age < age_of_oldboy:
                   print("think bigger!")
             else:
                   pirnt("think smaller......")
              count +=1
              if count == 3
                  countine_confirm = input("do you want to keep guessing..?")  
                   if countine_confirm !="n": #  不等于“n”继续循环
                          count = 0
    View Code
  • 相关阅读:
    洛谷八连测R7 nzhtl1477-我回来了
    String中的equals方法原理分析
    Java线程
    Spring配置日志级别报红:Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'logging.level' to java.util.Map<java.lang.String
    # SpringMVC跨服务器上传文件出现的问题
    使用Maven创建Spring-web项目的基本流程
    Maven的下载与安装(环境变量的配置)
    eNSP的安装(附链接)
    数据库分页操作
    Sql语句占位符?的使用
  • 原文地址:https://www.cnblogs.com/lzhn/p/7805835.html
Copyright © 2020-2023  润新知