Learn Python The Hard Way学習(31)-選択する

2492 ワード

以前の練習では、関数を印刷して呼び出し、すべてのプログラムが上から下まで実行されていました.関数を書いたら、実行するときに自分でどのブランチを実行するかを選択する必要があります.if、else、elifで実現できます.
前の練習は簡単な質問セットにすぎません.次の練習では、質問を提出し、ユーザーが自分で答えを選択します.
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'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 = 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 id 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 survies 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文が含まれていることであり、このネストは非常に強く、よく使われています.
実行結果
root@he-desktop:~/mystuff# python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake, What do you do?
1. Take the cake.
2. Scream at the bear.
> 1
The bear eats your face off. Good job!
root@he-desktop:~/mystuff# python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 1
Your body survies powered by a mind of jello. Good job!
root@he-desktop:~/mystuff#
加点練習
上のゲームを拡張して、新しい判断を追加します.