zoukankan      html  css  js  c++  java
  • 018 分支

    • 三种结构:顺序、分支、循环

    顺序

    • 顾名思义,就是自上而下,顺序执行

    分支

    基本语法

    if 条件表达式:
        语句1
        语句2
        语句3
        ...
    
    1. 条件表达式后面的冒号不能少
    2. 属于 if 的语句必须使用同一缩进

    例1

    age = 17
    if age < 18:
        print("孩子,来这里的都是成年人!")
        print("等你成年了再来!")
        print("再等一年吧!")
    

    例2

    age = 19
    if age < 18:
        print("孩子,来这里的都是成年人!")
        print("等你成年了再来!")
        print("再等一年吧!")
    print("孩子,两年了,又见面了。等什么呢?赶紧上车吧!")
    

    例3

    age = 19
    if age < 18:
        print("孩子,来这里的都是成年人!")
        print("等你成年了再来!")
    print("再等一年吧!")
    print("骗你的。还等什么呢?赶紧上车吧!")
    

    双向分支

    if 条件表达式:
        语句1
        语句2
        ...
    else:
        语句3
        语句4
        ...
    

    补充:input()

    1. 括号中可以写入字符串,运行时执行到这一句,会在屏幕上显示该字符串
    2. 括号内的字符串常用于“友情提醒”
    3. input() 能接受用户输入的内容并返回到程序
    4. input() 返回的内容一定是字符串类型
    name = input("What's your name?")
    print("Welcome, " + name + " !")
    

    例1

    gender = input("Please enter your gender(male/female): ")
    print("Your gender is: {0}".format(gender))
    
    if gender == "male":
        print("OK, next.")
    else:
        print("Welcome!")
    

    例2

    score = int(input("Please enter your score: "))
    
    if score >= 90:
        print("A")
    if 80 <= score < 90:
        print("B")
    if 70 <= score < 80:
        print("C")
    if 60 <= score < 70:
        print("D")
    if score < 60:
        print("I’m sorry!")
    

    多路分支

    • 超过两路分支的情况,简称多路分支
    if 条件表达式1:
        语句1
        ...
    elif 条件表达式2:
        语句2
        ...
    elif 条件表达式3:
        语句3
        ...
    ...
    else:
        语句4
        ...
    
    • elif 可以有多个
    • else 可选
    • 与双向分支一样,多路分支只会选一个分支执行

    举例

    # score = int(input("Please enter your score: "))
    score = 90  # 方便起见,直接赋个值
    
    if score >= 90:
        print("A")
    elif score >= 80:
        print("B")
    elif score >= 70:
        print("C")
    elif score >=60 :
        print("D")
    else:
        print("I'm sorry!")
    

    注意

    • if-else 可以嵌套使用
    • Python 没有 switch-case 语句,因为 switch-case 不常用,且可以用 if-else 替代

    循环

  • 相关阅读:
    那些年,学swift踩过的坑
    JAVA经BigDecimal圆角的解决方案及注意事项
    Jquery简介选择的
    Oracle性能优化顺序表名称来选择最有效的学习笔记
    jQuery Validate插入 reomte使用详细的说明
    公钥私人 ssh避password登陆
    Telnet,SSH1,SSH2,Telnet/SSL,Rlogin,Serial,TAPI,RAW
    mysqlbackup 还原特定的表
    OpenJDK 阅读源代码 Java 实现字节流输入类
    Android Application Thread CPU GC Operatiing and OOM Question 0603-随手笔记
  • 原文地址:https://www.cnblogs.com/yorkyu/p/10297612.html
Copyright © 2011-2022 走看看