美文网首页笨办法学Python
《笨办法学Python》21-----条件判断

《笨办法学Python》21-----条件判断

作者: 大猫黄 | 来源:发表于2016-02-25 15:51 被阅读147次

条件判断在程序的重要组成部分,一段智能化的程序中必然包含有条件判断语句。

条件判断语句格式:

if 表达式1:

    代码1

elif 表达式2:

    代码2

else:

    代码3

如果表达式1为真,则执行代码1;

如果表达式1为假且表达式2为真,则执行代码2;

如果表达式1和表达式2都为假则执行代码3.

条件语句可以嵌套使用,以便进行更智能化的判断。

注意语法格式:

1.表达式后跟冒号

2.缩进

教材代码

print "You enter a dark room with two doors. do you  go through door 1 or door 2?"

door = raw_input(">")

if door =="1":

    print "There is a giant bear here eating a cheese cake. what do you do?"

    print "1. Take the cake."

    print "2. Scream at the bear."

    bear = raw_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 %s is probably better. bear runs away." % bear

elif door == "2":

    print "You stare into the endless abyss at cthulhu's retina."

    print "1. blueberries."

    print "2. yellow jacket clothespins."

    print "3. understanding revolvers yelling melodies."

    insanity = raw_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."

这是个文字游戏程序,条件语句进行了2层嵌套。

相关文章

  • 《笨办法学Python》21-----条件判断

    条件判断在程序的重要组成部分,一段智能化的程序中必然包含有条件判断语句。 条件判断语句格式: if 表达式1: ...

  • 一个超级小白的Python学习日记(二)

    按照“笨办法”学Python ,目前该书已经看到习题20。几个体会: 关于“笨办法” “笨办法”是一种让你很不舒服...

  • 《笨办法学python》笨的人一样能学会python,电子版 和

    《笨办法学python》 译者前言《笨办法学Python》(Learn Python The Hard Way,简...

  • 6章 条件判断

    本章大纲 常见流程控制 if条件判断 复合条件判断 常见流程控制 if条件判断 Python 不支持swirch ...

  • python--控制流程

    python的控制流程可以分为:条件判断,三目运算,条件循环,迭代循环。条件判断: 注意:在每个判断条件后面是由 ...

  • Python练习——判断和循环

    Python 基础总结 (判断和循环) 条件判断 循环结构

  • Python:If 条件判断

    If 和else最后面必须加:冒号。使用if语句来打印不同年龄的内容。 简单点: 复杂点:增加else if,简写...

  • Python:条件判断

    计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。比如,输入用户年龄,根据年龄打印不同的内容,在Pyth...

  • Python条件判断

    人生就是由一些列的选择构成的,我们时刻都在进行判断。 那么在程序当中,我们如何实现选择判断的功能呢?先看一个程序框...

  • python条件判断

    与计算机沟通的逻辑:条件判断 让计算机明确,在什么条件下,做什么? if XXX #条件 print(XXX...

网友评论

    本文标题:《笨办法学Python》21-----条件判断

    本文链接:https://www.haomeiwen.com/subject/zugikttx.html