zoukankan      html  css  js  c++  java
  • 表达式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
  • 相关阅读:
    C# IP地址与数字之间的互转
    C# 获取本机的所有ip地址,并过滤内网ip
    C# POST数据base64到接口会出错的问题
    C# 使用 Task 替换 ThreadPool ,异步监测所有线程(任务)是否全部执行完毕
    C# 线程池执行操作例子
    输入及词法分析详解
    用java实现编译器-算术表达式及其语法解析器的实现
    用java实现一个简易编译器-语法解析
    用java实现一个简易编译器1-词法解析入门
    模板方法模式
  • 原文地址:https://www.cnblogs.com/lzhn/p/7805835.html
Copyright © 2011-2022 走看看