Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著

的学习思路和理解,如有不如之处,望指出!!!

这一节我们用前面学习过的if语句、for语句、while语句和def定义函数等来做一个小游戏

[TOC]

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# ex35.py

from

def
print
next=raw_input("> "
if
how_much=int(next)
else
dead("man,learn to type a number."
if
print
exit(0
else
dead("You greedy bastard!"

def
print
print
print
print
bear_moved=False
while
next=raw_input("> "
if
dead("the bear looks at you then slaps your face off."
elif
print
bear_moved=True
elif
dead("the bear gets pissed off and chews your leg off."
elif
gold_room()
else
print

def
print
print
print
next=raw_input("> "
if
start()
elif
dead("well that was tasty!"
else
cthulhu_room()

def
print
exit(0
def
print
print
print
next=raw_input("> "
if
bear_room()
elif
cthulhu_room()
else
dead("you stumble around the room until you starve."
start()

这是一个选择的小游戏,每次不同的选择都会有不同的结果

建议仔细看这个代码,搞清楚逻辑关系

你可以看到的结果

本节需要注意的知识

  1. exit()语句

exit()可以中断某个程序,而其中的数字参数则用来表示程序是否遇到错误而中断。

exit(0)表示程序是正常退出的

exit(1)表示发生了错误,可以用不一样的数字代表不同的错误结果。

比如,你可以用exit(100)来表示另一种和exit(2)exit(1)不同的错误

  1. int()指令

int() 函数用于将一个字符串或数字转换为整型。

语法

1
class

参数

  • x – 字符串或数字。

  • base – 进制数,默认十进制。

示例

1
2
3
4
5
6
7
8
9
10
11
12
>>>int()               # 不传入参数时,得到结果0
0
>>>
3
>>>
3
>>>
18
>>>
10
>>>
8
  1. 为什么写while True

这样可以创建一个无限循环


这是**《笨方法学Python》**的第十九篇文章

希望自己可以坚持下去

希望你也可以坚持下去