前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >习题28:作出决定

习题28:作出决定

作者头像
py3study
发布2018-08-02 11:33:10
2310
发布2018-08-02 11:33:10
举报
文章被收录于专栏:python3python3

多实践,多练习

练习代码如下:

代码语言:javascript
复制
# coding: utf-8
__author__ = 'www.py3study.com'
print("You enter a dark room with two doors.Do you go through door #1 or door #2 ?")
door = input(">>")
if door == '1':
    print("There's a giant bear here eating a cheese cake. What do you do ?")
    print("1. Take the cake.")
    print("2. Scream at the bear.")
    bear = input(">>")
    if bear == '1':
        print("The bear eats your face off. Good job!")
    elif bear == '2':
        print("The bear eats your legs off. Good job!")
    else:
        print("Well, doing {} is probably better. Bear runs away.".format(bear))
elif door == '2':
    print("You stare into the endless abyss at Cthulhu's retina.")
    print("1. Blueberries.")
    print("2. Yellow jacket clotherpins.")
    print("3. Understanding revolvers yelling melodies.")
    insanity = input(">>")
    if insanity == '1' or insanity == '2':
        print("Your body survives powered by a mind of jello. Good job !")
    else:
        print("The insanity rots your eyes into a pool of muck. Good job !")
else:
    print("You stumble around and fall on a knife and die. Good job !")

这里的重点是你可以在"if语句"内部再放一个“if语句”,这是一个很强大的功能,可以用来创建嵌套(nested)的决定,其中的一个分支将引向另一个分支的子分支

应该看到的结果

图片.png
图片.png

上面的列子有更多的选择,这里就不演示了

常见问题

可以用多个if/else来取代elif吗?

有时候可以,不过这也取决于if/else是怎么样写的。而且这样一来python就需要去检测每一处if/else,而不是像if/elif/else一样,只需要检查到第一个True就可以停下来了

怎么判断一个数字处于某个值域中?

两个办法:经典语法是使用1<x<10,或者用x in range(1,10)也可以

怎样用if/elif/else区块实现四个以上的条件判断?

简单,多写几个elif区块就可以了

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-11-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档