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

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

条件判断语句格式:

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-----条件判断)