zoukankan      html  css  js  c++  java
  • python学习笔记(二)——程序结构

    1. 选择结构:

    if 语句:单分支、双分支、多分支

    **单分支结构**
    if 条件表达式:
    	语句块
    
    **双分支结构**
    if 条件表达式:
    	语句块
    else:
    	语句块
        
    **多分支结构**
    if 条件表达式1:
    	语句块
    elif 条件表达式2:
    	语句块
    elif 条件表达式3:
    	语句块
    else# 可以没有
    	语句块
    
    

    2. 循环结构:

    在python 中 for 循环与while 循环除了执行自己的循环体外,还可以使用break、continue、pass(空语句)等语句。

    2.1 for循环结构
    for 变量 in 序列类型:
    	循环体
      
    # 使用场景1
    >>> for i in range(11):
    ...     print(i,end=" ")		# end=" " 表示不换行输出
    ...
    0 1 2 3 4 5 6 7 8 9 10 
    # 使用场景1
    >>> str = "string"
    >>> for i in range(len(str)):
    ...     print(str[i],end="")
    ...
    string
    
    

    带 else 的for 循环

    for 变量 in 序列类型:
    	循环体
    else:
    	语句块
        
    
    # 使用场景 file.py
    sites = ["Baidu", "Google","Taobao","Tianmao"]
    for site in sites:
        if site == "Taobao":
            print("天猫!")
            break
        print("循环数据 " + site)
    else:
        print("没有循环数据!")
    print("完成循环!")
    
    # python file.py 输出 
    循环数据 Baidu
    循环数据 Google
    天猫!
    完成循环!
    
    # 注意,如果for循环体中没有break,程序在循环结束后会继续执行else后的语句块
    for i in [0,1]:
        print(i,end=" ")
    else:
        print("else")
    # 执行结果中有 else   
    0 1 else
    
    2.2 while循环语句
    while 条件表达式:
    	循环体
    else:
    	语句块
    	
    # 使用场景——无限循环
    >>> while(1):
    ...     input("input:")
    ...
    input:1
    '1'
    使用 Ctrl + C 结束
    
    # 使用场景——循环输出数字,并判断大小
    count = 0
    while count < 5:
    	print (count, " 小于 5")
    	count = count + 1
    else:
    	print (count, " 大于或等于 5")
       
    # 输出:
    0  小于 5
    1  小于 5
    2  小于 5
    3  小于 5
    4  小于 5
    5  大于或等于 5
    
    # 使用场景——简单语句组
    flag = 1
    while (flag): print ('循环执行中……!')
    print ("Good bye!")
    # 如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中
    
  • 相关阅读:
    Web安全实践
    认证授权的设计与实现
    Elasticsearch 分页查询
    【算法】三色旗
    【转】互联网项目中mysql应该选什么事务隔离级别
    Elasticsearch 聚合
    Elasticsearch 结构化搜索、keyword、Term查询
    Elasticsearch 单字符串多字段查询
    Elasticsearch 复合查询——多字符串多字段查询
    JavaScript 原型与原型链
  • 原文地址:https://www.cnblogs.com/TaoR320/p/12680130.html
Copyright © 2011-2022 走看看