您的位置:首页 > 编程语言 > Python开发

笨办法学Python-习题32-36

2018-01-24 14:19 316 查看
习题32:

1.关于range简单的用法

2.可行

3.喜闻乐见的菜鸟教程-列表

习题33:

在写函数的时候,发现我定义在函数之外的变量无法用在函数中

出现了这样的错误:local variable 'i' referenced before assignment

然后找到了解决办法

点击打开链接

看来python的作用域和java,c还是有区别的 找了篇关于作用域的文章

Python 五个知识点搞定作用域

加分习题部分代码

i=0
numbers=[]

def loop(i):
while i<6:
print "At the top i is ",i
numbers.append(i)
i=i+1
print "numbers now:",numbers
print "the bottom i is",i

loop(3)
print numbers
def for_loop():
for i in range(1,6):
numbers.append(i)
print "numbers now:",numbers
for_loop()习题34:
从零开始的程序员生活~

习题35:

在python中可以使用in符号判断指定的元素是否存在于列表中

关于in的操作

5.这样通过检查0,1判断是否为数字

假设输入的是22 不存在0,1 就不会被认为是数字

这是更改后的代码

from sys import exit

def gold_room():
print "This room is full of gold. How much do you take?"
next=raw_input(">")
if next.isdigit():
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 Cthulh."
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 i
4000
s 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.")

gold_room()

习题36:
If 语句的规则

1. 每一个“if 语句”必须包含一个 else.(不知道什么意思,反正可以不写)

2. 如果这个 else 永远都不应该被执行到,因为它本身没有任何意义,那你必须在else 语句后面使用一个叫做 die 的函数,让它打印出错误信息并且死给你看,这和上一节的习题类似,这样你可以找到很多的错误。(没试过)

3. “if 语句”的嵌套不要超过 2 层,最好尽量保持只有 1 层。这意味着如果你在 if 里边又有了一个 if,那你就需要把第二个 if 移到另一个函数里面。(以python对缩进严格情况来看,有必要)

4. 将“if 语句”当做段落来对待,其中的每一个 if, elif, else 组合就跟一个段落的句子组合一样。在这种组合的最前面和最后面留一个空行以作区分。

5. 你的布尔测试应该很简单,如果它们很复杂的话,你需要将它们的运算事先放到一个变量里,并且为变量取一个好名字。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: