• 流程控制if、while、for


    一 if

    if 条件1:
    
        缩进的代码块
    
      elif 条件2:
    
        缩进的代码块
    
      elif 条件3:
    
        缩进的代码块
    
      ......
    
      else:  
    
        缩进的代码块

    二 while

    不用写重复代码又能让程序重复一段代码多次呢? 循环语句就派上用场啦
    
    while 条件:    
        # 循环体
     
        # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
        # 如果条件为假,那么循环体不执行,循环终止
    
    continue和break

    死循环

    import time
    num=0
    while True:
        print('count',num)
        time.sleep(1)
        num+=1   

    嵌套循环

    tag=True  #tag用来控制循环的退出很有用
    
      while tag:
    
        ......
    
        while tag:
    
          ........
    
          while tag:
    
            tag=False


    例如: 给3次机会猜年龄
    age=20
    tag=1

    while tag<4:
    guess_age=int(raw_input("please input age:"))
    tag+=1
    if guess_age>age:
    print("you guess right")
    break
    else:
    print("you guess wrong")
    continue


    例如: 三级菜单(while 多层嵌套的使用),输入除了"quit"和"quit_all"的任意字符串会进入下一层循环,输入quit返回上一层,输入quit_all退出所有循环.
    tag=True #tag 在这里控制所有循环的退出

    while tag:
    print("Level1")
    choice=raw_input("level1>>:")
    if choice == "quit": break
    if choice == "quit_all": tag=False

    while tag:
    print("Level2")
    choice = raw_input("level2>>:")
    if choice == "quit": break
    if choice == "quit_all": tag = False

    while tag:
    print("Level3")
    choice = raw_input("level1>>:")
    if choice == "quit": break
    if choice == "quit_all": tag = False



    三 for

    1 迭代式循环:for,语法如下

      for i in range(10):

        缩进的代码块

    2 break与continue(同上)

    3 循环嵌套

    九久乘法表
    
    for i in range(1,10):
        for j in range(1,i+1):
            print('%s*%s=%s' %(i,j,i*j),end=' ')
        print()
    金字塔
    
    #分析
    '''
    
                 #max_level=5
        *        #current_level=1,空格数=4,*号数=1
       ***       #current_level=2,空格数=3,*号数=3
      *****      #current_level=3,空格数=2,*号数=5
     *******     #current_level=4,空格数=1,*号数=7
    *********    #current_level=5,空格数=0,*号数=9
    
    #数学表达式
    空格数=max_level-current_level
    *号数=2*current_level-1
    
    '''
    
    #实现
    max_level=5
    for current_level in range(1,max_level+1):
        for i in range(max_level-current_level):
            print(' ',end='') #在一行中连续打印多个空格
        for j in range(2*current_level-1):
            print('*',end='') #在一行中连续打印多个空格
        print()
    
    打印金字塔
  • 相关阅读:
    tomcat项目部署后,无法弹出浏览器窗口,IDEA控制台如何快速找到错误日志
    导入新的jar包后,提示ClassNotFoundException 怎么解决?
    Vue is not defined
    next(),nextLine(),nextInt的区别
    Properties类与流的相关方法,properties的键与值都应该是字符串
    Java并发编程从入门到精通
    Java并发编程从入门到精通
    Java并发编程从入门到精通
    Java并发编程从入门到精通
    Java并发编程从入门到精通
  • 原文地址:https://www.cnblogs.com/yitianyouyitian/p/8617184.html
Copyright © 2020-2023  润新知