学习python的第十八天


访问列表的元素

列表的作用很大,但是只有在访问它们的时候才能发挥作用,这节学习如何调用列表中的某些元素。访问第一个元素的方法这样的:

animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]

Python和数学一样,列表是从0开始的,虽然看起来比较奇怪,但是这样是有好处的。ordinal == 有序,从1开始;cardinal == 随机选取,从0开始。

练习部分

animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print '1. The animal at %s' % animals[1]
print '2. The %s animal.' % animals[2]
print '3. The %s animal.' % animals[0]
print '4. The animal at %s.' % animals[3]
print '5. The %s animal.' % animals[4]
print '6. The animal at %s.' % animals[2]
print '7. The %s animal.' % animals[5]
print '8. The animal at %s.' % animals[4]

加分习题

1.互相翻译
word = raw_input("Please enter the word: \n> ")
if word == 'book':
    word = str(word)
    print "书"

运行结果是:

Please enter the word: 
> book
书

分支和函数

练习部分

from sys import exit

def gold_room():
    print "This room is full of gold. How much do you take?"
    next = raw_input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")
    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")

def bear_room():
    print "There is a bear here."
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door."
    print "How are you going to move the bear?"

    bear_moved = False

    while True:
        next = raw_input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif next == "taunt bear" and not bear_moved:
            print "The bear has moved from the door. You can go through it now."
            bear_moved = True
        elif next == "taunt bear" and  bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print "I got no idea what that means."

def cthulhu_room():
    print "Here you see the great evil Cthulhu."
    print "He, it, whatever stares at you and you go insane."
    print "Do you flee for your life or eat your head?"

    next = raw_input("> ")

    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulhu_room()

def dead(why):
    print why, "Good job!"
    exit(0)

def start():
    print "You are in a dark room."
    print "There is a door to your right and left."
    print "Which one do you take?"

    next = raw_input("> ")
    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")

start()

加分习题

1.地图

地图

2.修改以后的代码
from sys import exit

q = "*" * 20

def start():
    print "You are in a dark room.\n"
    print "There is a door to your right and left.\n"
    print "Which one do you take?\n"
    print q,"\n"
    next = raw_input("> ")
    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")

def bear_room():
    print "There is a bear here.\n"
    print "The bear has a bunch of honey.\n"
    print "The fat bear is in front of another door.\n"
    print "How are you going to move the bear?\n"
    print q, "\n"
    bear_moved = False

    while True:
        next = raw_input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.\n")
        elif next == "taunt bear" and not bear_moved:
            print "The bear has moved from the door. You can go through it now.\n"
            bear_moved = True
        elif next == "taunt bear" and  bear_moved:
            dead("The bear gets pissed off and chews your leg off.\n")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print "I got no idea what that means.\n"

def cthulhu_room():
    print "Here you see the great evil Cthulhu.\n"
    print "He, it, whatever stares at you and you go insane.\n"
    print "Do you flee for your life or eat your head?\n"
    print q,"\n"

    next = raw_input("> ")

    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!\n")
    else:
        cthulhu_room()

def gold_room():
    print "This room is full of gold. How much do you take?\n"

    next = raw_input("> ")

    if "0" in next or "1" in next: #暂时解决不了,用其他方式判断是否输入的是数字
        how_much = int(next)
    else:
        dead("Man, learn to type a number.\n")

    if how_much < 50:
        print "Nice, you're not greedy, you win!\n"
        exit(0)
    else:
        dead("You greedy bastard!\n")

def dead(why):
    print why, "\nGood job!\n"
    exit(0)

start()

设计和调试

if语句的规则

  1. 每一个语句必须包含一个 else
  2. 如果这个 else 永远都不应该被执行到,因为它本身没有任何意义,那你必须在 else 语句后面使用一个叫做 die 的函数,让它打印出错误信息并且死给你看,这和上一节的习题类似,这样你可以找到很多的错误。
  3. if语句的嵌套不要超过 2 层,最好尽量保持只有 1 层。这意味着如果你在 if 里边又有了一个 if,那你就需要把第二个 if 移到另一个函数里面。
  4. if语句当做段落来对待,其中的每一个 if, elif, else 组合就跟一个段落的句子组合一样。在这种组合的最前面和最后面留一个空行以作区分。
  5. 你的布尔测试应该很简单,如果它们很复杂的话,你需要将它们的运算事先放到一个变量里,并且为变量取一个好名字。

循环语句的规则

  1. 只有在循环永不停止时使用while循环,这意味着你可能永远都用不到。这条只有Python中成立,其他的语言另当别论。
  2. 其他类型的循环都使用for循环,尤其是在循环的对象数量固定或者有限的情况下。

调试(debug)的小技巧

  1. 不要使用 debuggerDebugger所作的相当于对病人的全身扫描。你并不会得到某方面的有用信息,而且你会发现它输出的信息态度,而且大部分没有用,或者只会让你更困惑。
  2. 最好的调试程序的方法是使用 print 在各个你想要检查的关键环节将关键变量打印出来,从而检查哪里是否有错。
  3. 让程序一部分一部分地运行起来。不要等一个很长的脚本写完后才去运行它。写一点,运行一点,再修改一点。

家庭作业

写一个和上节练习类似的游戏。同类的任何题材的游戏都可以,花一个星期让它尽可能有趣一些。作为加分习题,你可以尽量多使用列表、函数、以及模组(记得习题 13 吗?),而且尽量多弄一些新的 Python代码让你的游戏跑起来。不过有一点需要注意,你应该把游戏的设计先写出来。在你写代码之前,你应该设计出游戏的地图,创建出玩家会碰到的房间、怪物、以及陷阱等环节。一旦搞定了地图,你就可以写代码了。如果你发现地图有问题,就调整一下地图,让代码和地图互相符合。

最后一个建议:每一个程序员在开始一个新的大项目时,都会被非理性的恐惧影响到。为了避免这种恐惧,他们会拖延时间,到最后一事无成。我有时会这样,每个人都会有这样的经历,避免这种情况的最好的方法是把自己要做的事情列出来,一次完成一样。开始做吧。先做一个小一点的版本,扩充它让它变大,把自己要完成的事情一一列出来,然后逐个完成就可以了。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号