习题27:if和else

发布时间:2017-11-15 15:20:25编辑:Run阅读(4765)

    1 你认为if对于它下一行的代码做了什么?

    if语句为代码创建了一个所谓的"分支",就跟RPG游戏中的情节分支一样,if语句告诉你的脚本:“如果这个布尔表达式为真,就运行接下来的代码,否则就跳过这一段”

    2 为什么if语句的下一行需要4个空格的缩进?

    行尾的冒号的作用是告诉python接下来你要创建一个新的代码区段,这跟创建函数的冒号是一个道理

    3 如果不缩进,会发生什么事情?

    如果你没有缩进,应该会看到python报错,python规则里,只要一行以“冒号”:结尾,它接下来的内容就应该有缩进

    4 把习题27中的其它布尔表达式放到if语句中会不会也可以运行呢?

    可以,而且不管多复杂都可以,虽然写复杂的东西通常是一种不好的编程风格

    5 如果把变量people,cats和dogs的初始值改掉,会发生什么事情?

    因为你比较的对象是数字,如果你把这些数字改掉的话,某些位置的if语句会被演绎为True,而它下面的代码区段将被运行

    练习代码如下:

    # coding: utf-8
    __author__ = 'www.py3study.com'
    people = 30
    cars = 40
    buses = 15
    if cars > people:
       print("We should take the cars.")
    elif cars < people:
       print("We should not take the cars.")
    else:
       print("We can't decide.")

    if buses > cars:
       print("That's too many buses.")
    elif buses < cars:
       print("Maybe we could take the buses.")
    else:
       print("We still can't decide.")

    if people > buses:
       print("Alright, let's just table the buses.")
    else:
       print("Fine,let's stay home then.")

    应该看到的结果

    C:\python\python.exe E:/test/lianxi_27.py
    We should take the cars.
    Maybe we could take the buses.
    Alright, let's just table the buses.


    常见问题

    如歌多个elif区块都是True,python会如何处理?

    python只会运行它碰到True的第一个区块,所以只有第一个为True的区块会被运行



关键字