笨方法学Python(31-35)

来源:互联网 发布:网络计算机与淘宝 编辑:程序博客网 时间:2024/06/08 20:17

习题31、作出决定

#!/usr/bin/python# -*- coding:utf-8 -*-print "You enter a dar room with two doors. Do you go through door #1 or door #2?"door = raw_input(">")if door == "1":    print "There's a giant beer 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 eates 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 ruans away." % bearelif door== "2":    print "You stare into the endlsee abyss at Cthulhu's retina."    print "1. Bluebeeries."    print "2. Yellow jacket clothespins."    print "3. Understanding revolvers yelling mlodies."    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!"

小结

  1. 可以用多个if/else来取代elif吗?
    有时候可以,不过这也取决于额 if/else是怎样写的,而且这样一来 python 就需要去检查每一处 if/else,而不是像if/elif/else一样,只要检查到第一个True就可以停下来了。
  2. 怎样判断一个数字处于某个值域中?
    两个办法:经典语法是使用1 < x < 10,或者用x in range(1, 10)也可以。
  3. 怎样用if/elif/else 区块实现四个以上的条件判断?
    简单,多写几个 elif 区块就可以了。

习题32、循环和列表

列表(list),顾名思义,它就是一个按顺序存放东西的容器。列表并不复杂,你只是要学习一点新的语法。首先我们看看如何创建列表:

hairs = ['brown', 'blond', 'red']eyes = ['brown', 'blue', 'green']weights = [1, 2, 3, 4]

你要做的是以 [(左方括号)开头“打开”列表,然后写下你要放入列表的东西,用逗号隔开,就跟函数的参数一样,最后你需要用](右方括号)结束右方括号的定义。然后 Python 接收这个列表以及里边所有的内容,将其赋给一个变量。

#!/usr/bin/python# -*- coding:utf-8 -*-the_count = [1, 2, 3, 4, 5]fruits = ['apples', 'oranges', 'pears', 'apricots']change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a listfor number in the_count:    print "This is count %d " % number# same as abovefor fruit in fruits:    print "A fruit of type: %s " % fruitfor i in change:     print "I got %r" % ielements = []for i in range(0, 6):    print "Adding %d to the list." % i    elements.append(i)for i in elements:    print "Element was: %d" % i 

小结

  1. 如何创建二维列表?
    就是在列表中包含列表,例如这样:[[1,2,3],[4,5,6]]
  2. 列表和数组不是一样的吗?
    取决于语言和实现方式。从经典意义上理解的话,列表和数组是很不同的,因为它们的实现方式不同。在 Ruby 语言中列表和数组都被叫做数组,而在 Python 中又都叫做列表。现在我们就把它叫列表吧,因为 Python 里就是这么叫的。
  3. 为什么 for-loop 可以使用未定义的变量?
    循环开始时这个变量就被定义了,当然每次循环它都会被重新定义一次。
  4. 为什么for i in range(1, 3):只循环 2 次而非 3 次?
    range()函数会从第一个数到最后一个,但不包含最后一个数字。所以它在 2 的时候就停
    止了,而不会数到 3。这种含首不含尾的方式是循环中及其常见的一种用法。
  5. elements.append()是什么功能?
    它的功能是在列表的尾部追加元素。打开 Python 命令行,创建几个列表试验一下。以后每
    次碰到自己不明白的东西,你都可以在 Python 的交互式命令行中实验一下。

习题33、While 循环

While 循环有一个问题,那就是有时它会永不结束。如果你的目的是循环到宇宙毁灭为止,那这样也挺好的,不过其他的情况下你的循环总需要有一个结束点。

为了避免这样的问题,你需要遵循下面的规定:

  1. 尽量少用 while-loop,大部分时候 for-loop 是更好的选择。
  2. 重复检查你的 while 语句,确定你测试的布尔表达式最终会变成 False 。
  3. 如果不确定,就在 while-loop 的结尾打印出你要测试的值。看看它的变化。
#!/usr/bin/python# -*- coding:utf-8 -*-i = 0 numbers = []while i < 6:    print "At the top i is %d" % i    numbers.append(i)    i = i + 1    print "Number now: ", numbers    print "At the bottom i is %d" % iprint "The numbers:"for num in numbers:    print num

小结

  1. for-loopwhile-loop有何不同?
    for-loop只能对一些东西的集合进行循环,while-loop可以对任何对象进行驯化。然而,while-loop比起来更难弄对,而一般的任务用for-loop更容易一些。
  2. 循环好难理解啊,我该怎样理解?
    觉得循环不好理解,很大程度上是因为不会顺着代码的运行方式去理解代码。当循环开始时,它会运行整个区块,区块结束后回到开始的循环语句。如果想把整个过程视觉化,你可以在循环的各处塞入 print 语句,用来追踪变量的变化过程。你可以在循环之前、循环的第一句、循环中间、以及循环结尾都放一些 print 语句,研究最后的输出,并试着理解循环的工作过程。

习题34、访问列表的元素

记住: ordinal ==有序,以 1 开始;cardinal ==随机选取, 以 0 开始


习题35、分支和函数

#!/usr/bin/python# -*- coding:utf-8 -*-from sys import exitdef gold_room():    print "This room is full og 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 "Have 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 ringht 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. 为什么是while True:?
    这样可以创建一个无限循环。
  3. exit(0)有什么功能?
    在很多类型的操作系统里,exit(0) 可以中断某个程序,而其中的数字参数则用来表示程序是否是碰到错误而中断。exit(1)表示发生了错误,而exit(0)则表示程序是正常退出的。这和我们学的布尔逻辑0==False正好相反,不过你可以用不一样的数字表示不同的错误结果。比如你可以用exit(100)来表示另一种和exit(2)exit(1)不同的错误。
  4. 为什么raw_input()有时写成raw_input('> ')?
    raw_input的参数是一个会被打印出来的字符串,这个字符串一般用来提示用户输入。
0 0
原创粉丝点击