Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!
这一节我们用前面学习过的if
语句、for
语句、while
语句和def
定义函数等来做一个小游戏
源代码
# ex35.py
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()
这是一个选择的小游戏,每次不同的选择都会有不同的结果
建议仔细看这个代码,搞清楚逻辑关系
你可以看到的结果
本节需要注意的知识
exit()
语句
exit()
可以中断某个程序,而其中的数字参数则用来表示程序是否遇到错误而中断。
exit(0)
表示程序是正常退出的
exit(1)
表示发生了错误,可以用不一样的数字代表不同的错误结果。
比如,你可以用exit(100)
来表示另一种和exit(2)
或exit(1)
不同的错误
int()
指令
int()
函数用于将一个字符串或数字转换为整型。
语法
class int(x, base=10)
参数
x
– 字符串或数字。base
– 进制数,默认十进制。
示例
>>>int() # 不传入参数时,得到结果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16) # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
18
>>> int('0xa',16)
10
>>> int('10',8)
8
- 为什么写
while True
?
这样可以创建一个无限循环
这是**《笨方法学Python》**的第十九篇文章
希望自己可以坚持下去
希望你也可以坚持下去