以下来自《笨办法学Python3》,挺有意思的一本Python教学入门书籍。

HelloWorld

准备工作

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
# 当前系统使用RockyLinux9.2
# 使用普通用户登陆
# 安装程序
sudo dnf -y groupinstall development
sudo dnf -y installpython3 python3-devel python3-pip
# 配置pip源
cat > ~/.pip/pip.conf <<EOF
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host=mirrors.aliyun.com
EOF
# 升级pip
pip3 install --upgrade pip
# 配置vimrc
wget https://github.com/rkulla/pydiction/archive/master.zip
unzip -q master
mkdir -p ~/.vim/tools/pydiction
cp -r pydiction-master/after ~/.vim
cp pydiction-master/complete-dict ~/.vim/tools/pydiction/

cat > ~/.vimrc << EOF
" 加载插件
filetype plugin on
let g:pydiction_location = '~/.vim/tools/pydiction/complete-dict'
let g:pydiction_menu_height = 3

" 设置文件类型
set filetype=python
au BufNewFile,BufRead *.py,*.pyw setf python

"配置vimrc
set tabstop=2
set shiftwidth=2
set softtabstop=2
set autoindent
set smartindent
set nobackup
set expandtab
set number
set ruler
set nocompatible
set syntax=on
set encoding=utf-8
set fileformats=unix,dos
set showmatch
EOF

第一个程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[sujx@dev python]$ cat ex1.py 
print("Hello World!\n")
print("Hello Agin\n")
print("I like typing this.\n")
print("This is fun.\n")
print("Yay! Printing.\n")
print("I'd much rather your 'not'.\n")
print('I "said" do not touch this.\n')

[sujx@dev python]$ python ex1.py
Hello World!

Hello Agin

I like typing this.

This is fun.

Yay! Printing.

I'd much rather your 'not'.

I "said" do not touch this.

注释和#号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[sujx@dev python]$ cat ex2.py 
# Acomment, this is so you can read your program later.
# Anything after the # is ignored by python.

print("I could have code like.") # and the comment after is ignored

# You can also use a comment to "disable" or comment out code:
# print("This won't run.")

print("This will run.")

[sujx@dev python]$ python ex2.py
I could have code like.
This will run.

数字和数学计算

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
[sujx@dev python]$ cat ex3.py 
print("I will now count my chickens:")
print("Hens", 25 + 30 /6)
print("Roosters", 100 - 25 * 3 % 4 )
print("Now I will count the eggs:")

print(3 + 2 + 1 - 5 + 4 % 2 -1 / 4 +6)
print("Is it true that 3 + 2 < 5 - 7 ?")
print(3 + 2 < 5 -7)

print("What is 3 + 2?", 3+2)
print("What is 5 - 7", 5-7)

print("Oh, that's why it's False.")
print("How about some more.")

print("Is it greater?", 5 > -2)
print("Is it greate or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)

[sujx@dev python]$ python ex3.py
I will now count my chickens:
Hens 30.0
Roosters 97
Now I will count the eggs:
6.75
Is it true that 3 + 2 < 5 - 7 ?
False
What is 3 + 2? 5
What is 5 - 7 -2
Oh, that's why it's False.
How about some more.
Is it greater? True
Is it greate or equal? True
Is it less or equal? False

变量和命名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[sujx@dev python]$ cat ex4.py 
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven

print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")

[sujx@dev python]$ python ex4.py
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3.0 in each car.

更多的变量和打印

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
[sujx@dev python]$ cat ex5.py 
my_name = 'su jingxuan'
my_age = 42
my_height = 163 # cm
my_weight = 143 # kg
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'

print(f"Let's talk about {my_name}. ")
print(f"He's {my_height} cm tall.")
print(f"He's {my_weight} kg heavy. ")
print("Actually that's not too heavy. ")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on the coffee.")

# This line is tricky, try to get it exactly right.
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

[sujx@dev python]$ python ex5.py
Let's talk about su jingxuan.
He's 163 cm tall.
He's 143 kg heavy.
Actually that's not too heavy.
He's got Black eyes and Black hair.
His teeth are usually White depending on the coffee.
If I add 42, 163, and 143 I get 348.

字符串和文本

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
[sujx@dev python]$ cat ex6.py 
types_of_people = 10
x = f"There are {types_of_people} types of people."

binary = "binary"
do_not = "don't"
y = f"Those who konw {binary} and those who {do_not}."

print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")

hilarious = False
joke_evaluation = "Isn't that joke so funny? {}!"

print(joke_evaluation.format(hilarious))

w = "This is the left side of... "
e = "a string with a right side."

print(w + e)

[sujx@dev python]$ python ex6.py
There are 10 types of people.
Those who konw binary and those who don't.
I said: There are 10 types of people.
I also said: 'Those who konw binary and those who don't.'
Isn't that joke so funny? False!
This is the left side of... a string with a right side.

打印

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
[sujx@dev python]$ cat ex7.py 
print("Mary had a little lamb.")
print("Its fleece was white as {}.".format('snow'))
print("And everywhere that Mary went.")
print("." * 10) # What'd that do?

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

# Watch that comma at the end. try removing it to see what happens.
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
print(end7 + end8 + end9 + end10 + end11 + end12)

[sujx@dev python]$ python ex7.py
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
Cheese Burger

打印,打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[sujx@dev python]$ cat ex8.py 
formatter = "{} {} {} {}"

print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"Try your",
"Own text here",
"Maybe a poem",
"Or a song about fear"
))

[sujx@dev python]$ python ex8.py
1 2 3 4
one two three four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own text here Maybe a poem Or a song about fear

打印,打印,打印

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
[sujx@dev python]$ cat ex9.py 
# Here's some new strange stuff, remember type it exactly.

days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

print("Here are the days:", days)
print("Here are the months: ", months)

print("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")

[sujx@dev python]$ python ex9.py
Here are the days: Mon Tue Wed Thu Fri Sat Sun
Here are the months: Jan
Feb
Mar
Apr
May
Jun
Jul
Aug

There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.

转义符

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
[sujx@dev python]$ cat ex10.py 
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""

print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)

[sujx@dev python]$ python ex10.py
I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.

I'll do a list:
* Cat food
* Fishies
* Catnip
* Grass

输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[sujx@dev python]$ cat ex11.py 
print("How old are you?", end='')
age = input()
print("How tall are you?", end='')
height = input()
print("How much do you weight?", end='')
weight = input()

print(f"So, you're {age} old, {weight} heavy, and {height} tall.")

[sujx@dev python]$ cat ex12.py
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weight?")

print(f"So, you're {age} old, {weight} heavy, and {height} tall.")

[sujx@dev python]$ python ex11.py
How old are you?42
How tall are you?165cm
How much do you weight?73kg
So, you're 42 old, 73kg heavy, and 165cm tall.

基础

参数、解包和变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[sujx@dev python]$ cat ex13.py 
from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv

print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is:", third)

[sujx@dev python]$ python ex13.py 1st 2nd 3rd
The script is called: ex13.py
The first variable is: 1st
The second variable is: 2nd
The third variable is: 3rd

提示和传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from sys import argv

script, user_name = argv
prompt = '> '

print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you're a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)

print(f"Where do you live {user_name}")
lives = input(prompt)

print("What kind of computer do you have?")
computer = input(prompt)

print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}. Not sure where that is.
And you have a {computer} computer.
Nice.
""")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[sujx@dev python]$ python ex14.py xiaoming
Hi xiaoming, I'm the ex14.py script.
I'd like to ask you're a few questions.
Do you like me xiaoming?
> Yes
Where do you live xiaoming
> NewYork
What kind of computer do you have?
> Compaz

Alright, so you said Yes about liking me.
You live in NewYork. Not sure where that is.
And you have a Compaz computer.
Nice.

读取文件

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
[sujx@dev python]$ cat ex15.py 
from sys import argv

script, filename = argv
txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)
print(txt_again.read())

[sujx@dev python]$ python ex15.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

Type the filename again:
> ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

读写文件

代码

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
from sys import argv
script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w')

print("Truncating the file. Goodbye!")
target.truncate()

print("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
line4 = input("line 4: ")

print("I'm going to write these to the file.")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
target.write(line4)
target.write("\n")

print("And finally, we close it.")
target.close()

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[sujx@dev python]$ python ex16.py test.txt
We're going to erase test.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: 白日依山尽
line 2: 黄河入海流
line 3: 欲穷千里目
line 4: 更上一层楼
I'm going to write these to the file.
And finally, we close it.
[sujx@dev python]$ cat test.txt
白日依山尽
黄河入海流
欲穷千里目
更上一层楼

更多的文件操作

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}...")

# We could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()

print(f"The output file is {len(indata)} bytes long.")
print(f"Dose the output file exist? {exists(to_file)}")
print("Ready, hti RETURN to continue, CTRL-C to abort.")
input()

out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done.")

out_file.close()
in_file.close()

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
[sujx@dev python]$ python ex17.py test.txt target.txt
Copying from test.txt to target.txt...
The output file is 24 bytes long.
Dose the output file exist? True
Ready, hti RETURN to continue, CTRL-C to abort.

Alright, all done.

[sujx@dev python]$ cat target.txt
白日依山尽
黄河入海流
欲穷千里目
更上一层楼

命名、变量、代码和函数

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# This one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")

# Ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")

# This just takes one argument
def print_one(arg1):
print(f"arg1: {arg1}")

# This one takes on argument
def print_none():
print("I got nothing.")

print_two("Su","JingXaun")
print_two_again("Fang","Feng")
print_one("First!")
print_none()

执行

1
2
3
4
5
[sujx@dev python]$ python ex18.py
arg1: Su, arg2: JingXaun
arg1: Fang, arg2: Feng
arg1: First!
I got nothing.

函数和变量

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def cheese_and_crackers(cheese_count, boxes_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket.\n")

print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)

print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese,amount_of_crackers)

print("We can even do math inside too:")
cheese_and_crackers(10+20, 5+6)

print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[sujx@dev python]$ python ex19.py
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.

函数和文件

代码

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
from sys import argv

script, input_file = argv

def print_all(f):
print(f.read())

def rewind(f):
f.seek(0)

def print_a_line(line_count, f):
print(line_count, f.readline())

current_file = open(input_file)

print("First Let's print the whole file:\n")
print_all(current_file)

print("Now let's rewind, kind of like a tape.")
rewind(current_file)

print("Let's print three lines:")

current_line = 1
print_a_line(current_line, current_file)

current_line = 1 + 1
print_a_line(current_line, current_file)

current_line = 1 + 1
print_a_line(current_line, current_file)

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[sujx@zhangjiakou python]$ python ex20.py test.txt
First Let's print the whole file:

白日依山尽
黄河入海流
欲穷千里目
更上一层楼

Now let's rewind, kind of like a tape.
Let's print three lines:
1 白日依山尽

2 黄河入海流

2 欲穷千里目

函数返回值

代码

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
def add(a, b):
print(f"Addning {a} + {b}")
return a + b

def subtract(a,b):
print(f"SUBTRACTING {a} - {b}")
return a - b

def multiply(a,b):
print(f"MULTIPLYING {a} * {b}")
return a * b

def divide(a,b):
print(f"DIVDING {a} / {b}")
return a / b

print("Let's do some math with just functions!")

age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)

print(f"Age:{age}, Height:{height}, Weight:{weight}, IQ:{iq}")

# A puzzle for the extra credit, type is in anyway.
print("Here is a puzzle.")

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That become:", what, "Can you do it by hand?")

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
python ex21.py 
Let's do some math with just functions!
Addning 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVDING 100 / 2
Age:35, Height:74, Weight:180, IQ:50.0
Here is a puzzle.
DIVDING 50.0 / 2
MULTIPLYING 180 * 25.0
SUBTRACTING 74 - 4500.0
Addning 35 + -4426.0
That become: -4391.0 Can you do it by hand?

字符串*

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import sys
script, encoding, error = sys.argv

def main(language_file, encoding, errors):
line = language_file.readline()

if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)

def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors = errors)
cooked_string = raw_bytes.decode(encoding, errors = errors)

print(raw_bytes, "<===>", cooked_string)

languages = open("languages.txt", encoding = "utf-8")

main(languages, encoding, error)

执行

1
2
3
4
5
6
7
8
9
wget https://learnpythononthehardway.org/python3/languages.txt
python ex23.py utf-8 strict
b'\xd8\xa7\xd8\xb1\xd8\xaf\xd9\x88' <===> اردو
b'Ti\xe1\xba\xbfng Vi\xe1\xbb\x87t' <===> Tiếng Việt
b'V\xc3\xb5ro' <===> Võro
b'\xe6\x96\x87\xe8\xa8\x80' <===> 文言
b'\xe5\x90\xb4\xe8\xaf\xad' <===> 吴语
b'\xd7\x99\xd7\x99\xd6\xb4\xd7\x93\xd7\x99\xd7\xa9' <===> ייִדיש
b'\xe4\xb8\xad\xe6\x96\x87' <===> 中文

练习

练习1

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
print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
\n\t\twhere there is non.
"""

print("-------------------------")
print(poem)
print("-------------------------")

five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")

def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)

# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
# It's just like with an f"" string.
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10

print("We can also do that this way:")
formula = secret_formula(start_point)
# This is an easy way to apply a list to a format string.
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))

练习2

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
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words

def sort_words(words):
"""Sorts the words."""
return sorted(words)

def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print(word)

def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print(word)

def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)

def print_first_adn_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)

def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)

if语句

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
people = 20
cats = 30
dogs = 15

if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")

if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry.")

dogs += 5

if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")

if people == dogs:
print("People are dogs.")

执行

1
2
3
4
5
Too many cats! The world is doomed!
The world is dry.
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

else语句

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
people = 20
cats = 30
dogs = 15

if people < cats:
print("Too many cats! The world is doomed!")
elif people > cats:
print("Not many cats! The world is saved!")
else:
print("Eveybody have a cat!")

if people < dogs:
print("The world is drooled on!")
elif people > dogs:
print("The world is dry.")
else:
print("People are dogs.")

做出决定

代码

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
print("""
You enter a dark room with two doors.
Do you go through door #1 or door #2 ?
""")

door = input("> ")

if door == "1" :
print("There's a giant beat here eating a cheese cake.")
print("What do you do?")
print("1. Take the cake.")
print("2. Scream at bear.")

bear = input("> ")

if bear == "1":
print("The bear eat your face off. Good Job!")
elif bear == "2":
print("The bear eats your legs off. Good Job!")
else:
print(f"Well, doing {bear} is probably better.")
print("Bear run away.")

elif door == "2":
print("You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")

insanity = input("> ")

if insanity == "1" or insanity == "2":
print("Your body survives powered by a mind of jello.\nGood Job!")
else:
print("The insanity rots your eyes into a pool of muck.\nGood Job!")

else:
print("You stumble around and fail on a knife and die.\nGood Job!")

循环和列表

代码

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
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 'dimes', 3, 'quarters']

# This first kind of for-loop goes through a list
for number in the_count:
print(f"This is count {number}")

# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")

# Also we can go through mixed lists too
# Notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")

# we can also build lists, first start with an empty one
elements = []

# Then use the range function to do 0 to 5 counts
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)

# now we can print them out too
for i in elements:
print(f"Element was: {i}")

执行

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
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got pennies
I got dimes
I got 3
I got quarters
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

while循环

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
i = 0
numbers = []

while i< 6:
print(f"At the top i is {i}")
numbers.append(i)

i += 1
print("Number now:", numbers)
print(f"At the bottom i is {i}")

print("The numbers: ")

for num in numbers:
print(num)

执行

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
At the top i is 0
Number now: [0]
At the bottom i is 1
The numbers:
0
At the top i is 1
Number now: [0, 1]
At the bottom i is 2
The numbers:
0
1
At the top i is 2
Number now: [0, 1, 2]
At the bottom i is 3
The numbers:
0
1
2
At the top i is 3
Number now: [0, 1, 2, 3]
At the bottom i is 4
The numbers:
0
1
2
3
At the top i is 4
Number now: [0, 1, 2, 3, 4]
At the bottom i is 5
The numbers:
0
1
2
3
4
At the top i is 5
Number now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5

分支和函数

代码

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
65
66
67
68
69
70
71
72
73
from sys import exit

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

choice = input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
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 are 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:
choice = input("> ")

if choice == "take honey":
dead("The bear looks at you then slaps your face off.")
elif choice == "taunt bear" and not bear_moved:
print("The bear has moved from the door.")
print("You can go through it now.")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif choice == "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?")

choice = input("> ")

if "flee" in choice:
start()
elif "head" in choice:
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?")

choice = input("> ")

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

start()

列表的操作

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ten_things = "Apples Orange Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")

stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding:", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")

print("There we go: ", stuff)
print("Let's do some things with stuff.")

print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(stuff.pop())
print(stuff.pop())
print(''.join(stuff))
print('#'.join(stuff[3:5]))

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[sujx@zhangjiakou python]$ python ex38.py
Wait there are not 10 things in that list. Let's fix that.
Adding: Boy
There are 7 items now.
Adding: Girl
There are 8 items now.
Adding: Banana
There are 9 items now.
Adding: Corn
There are 10 items now.
There we go: ['Apples', 'Orange', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Orange
Corn
Corn
Banana
Girl
ApplesOrangeCrowsTelephoneLightSugarBoy
Telephone#Light

字典

代码

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
65
66
67
68
69
70
71
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}

# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonvile'
}

# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'PortLand'

# print out some cities
print('-' * 10)
print("NY State hae:", cities['NY'])
print("OR State has: ",cities['OR'])

# print out some states
print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])

# do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])

# print every state abbreviation
print("-" * 10)
for state, abbrev in list(cities.items()):
print(f"{state} is abbreviated {abbrev}")

# print every cities in state
print("-" * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has city {city}")

# now do both at the same time
print("-" * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")

print("-" * 10)
# safely get a abbreviation by state that might not be there
state = states.get("Texas")

if not state:
print("Sorry,no Texas")
states['Texas'] = 'TX'

# get a city with a default value
city = cities.get('TX', 'Does not Exist.')
print(f"The city for the state 'TX' is: {city}")
cities['TX'] = 'Austin'

print(list(cities.items()))
print(list(states.items()))

print("-" * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")

执行

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
----------
NY State hae: New York
OR State has: PortLand
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonvile
----------
CA is abbreviated San Francisco
MI is abbreviated Detroit
FL is abbreviated Jacksonvile
NY is abbreviated New York
OR is abbreviated PortLand
----------
CA has city San Francisco
MI has city Detroit
FL has city Jacksonvile
NY has city New York
OR has city PortLand
----------
Oregon state is abbreviated OR
and has city PortLand
Florida state is abbreviated FL
and has city Jacksonvile
California state is abbreviated CA
and has city San Francisco
New York state is abbreviated NY
and has city New York
Michigan state is abbreviated MI
and has city Detroit
----------
Sorry,no Texas
The city for the state 'TX' is: Does not Exist.
[('CA', 'San Francisco'), ('MI', 'Detroit'), ('FL', 'Jacksonvile'), ('NY', 'New York'), ('OR', 'PortLand'), ('TX', 'Austin')]
[('Oregon', 'OR'), ('Florida', 'FL'), ('California', 'CA'), ('New York', 'NY'), ('Michigan', 'MI'), ('Texas', 'TX')]
----------
Oregon state is abbreviated OR
and has city PortLand
Florida state is abbreviated FL
and has city Jacksonvile
California state is abbreviated CA
and has city San Francisco
New York state is abbreviated NY
and has city New York
Michigan state is abbreviated MI
and has city Detroit
Texas state is abbreviated TX
and has city Austin

提高

模块、类和对象

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics

def sing_me_a_song(self):
for line in self.lyrics:
print(line)

happy_body = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family"
"With pockets full of shells"])

happy_body.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

执行

1
2
3
4
Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around the familyWith pockets full of shells

基本的面向对象分析和设计

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
from sys import exit
from random import randint
from textwrap import dedent

class Scene(object):
def enter(self):
print("This scene is not yet configured.")
print("Subclass it and implement enter()")
exit(1)

class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')

while current_scene !=last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)

class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mon would be pround...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this.",
"You're worse than your Dad's jokes."
]
def enter(self):
print(Death.quips[randint(0, len(self.quips)-1)])
exit(1)

class CentralCorridor(Scene):
def enter(self):
print(dedent("""
The Kaju have invaded your ship and destroyed your entire crew.
"""))
action = input(">> ")

if action == "shoot!":
print(dedent("""
The Kaju eats you.
"""))
return 'death'
elif action == "dodge!":
print(dedent("""
You wakup shortly after only to die as the Gothon stomps on your head and eats you.
"""))
return 'death'
elif action == "tell a joke":
print(dedent("""
Gothon stops, tries not to laugh,then busts out laughing and can't move.
"""))
return 'laser_weapon_armory'
else:
print("DOES NOT COMPUTE!")
return 'central_corridor'

class LaserWeaponArmory(Scene):
def enter(self):
print(dedent("""
There's a keypad lock on the box and you need the code to get the bomb out.
If you get the code wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits.
"""))
code = f"{randint(1,9)} {randint(1,9)} {randint(1,9)}"
guess = input("[keypad]>> ")
guesses = 0
print(f"{code}")

while guess != code and guesses < 10:
print("BzzzeDDD!")
guesses += 1
guess = input("[keypad]>> ")

if guess == code:
print(dedent("""
You grab the neutron bomb and run as fast as you can to the bridge.
"""))
return 'the_bridge'
else:
print(dedent("""
The lock buzzes one last time and Gothons blow up the ship and you die.
"""))
return 'death'

class TheBridge(Scene):
def enter(self):
print(dedent("""
You brust onto the bridge.And There are 5 Gothons who are trying
to kill you.
"""))
action = input(">> ")
if action == "throw the bomb":
print(dedent("""
You die konwing they will probably blow up when ti goes off.
"""))
return 'death'
elif action == "slowly place the bomb":
print(dedent("""
Now that the bomb is placed you run to the escape pod to get off this tin can.
"""))
return 'escape_pod'
else:
print("DOES NOT COMPUTE!")
return "the_bridge"

class EscapePod(Scene):
def enter(self):
print(dedent("""
There's 5 pods, which one do you take?
"""))

good_pod = randint(1,5)
print(f"{good_pod}")
guess = input("[pod #]> ")

if int(guess) != good_pod:
print(dedent("""
You jump into pod {guess}. The pod escapes into the void of space.You die.
"""))
return 'death'
else:
print(dedent("""
You win!
"""))
return 'finished'

class Finished(Scene):
def enter(self):
print("You won! Good Job!")
return 'finished'

class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished()
}
def __init__(self, start_scene):
self.start_scene = start_scene

def next_scene(self, scene_name):
va1 = Map.scenes.get(scene_name)
return va1

def opening_scene(self):
return self.next_scene(self.start_scene)

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

初试身手

项目骨架

配置虚拟环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 安装工具
dnf install -y python3-setuptools
pip3 install --upgrade pip setuptools virtualenv nose
# 创建虚拟环境
mkdir ~/.venvs
virtualenv –system–site –packages ~/.venvs/lpthw
. ~/.venvs/lpthw/bin/activate
(lpthw) $ pip install nose

# 创建目录骨架
mkdir -pv projects/skeletion/{bin,NAME,tests,docs}
touch projects/skeletion/NAME/__init__.py
touch projects/skeletion/tests/__init__.py
touch projects/skeletion/setup.py
touch projects/skeletion/tests/NAME_tests.py

创建setup.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try:
from setuptools import setup
except ImportError:
from distutils.core import setup

config = {
'description': 'My Project',
'author': 'My Name',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'My email.',
'version': '0.1',
'install_requires': ['nose'],
'packages': ['NAME'],
'scripts': [],
'name': 'projectname'
}

setup(**config)

创建测试文件

1
2
3
4
5
6
7
8
from nose.tools import *
import NAME
def setup():
print("SETUP!")
def teardown():
print("TEAR DOWN!")
def test_basic():
print("I RAN!")

目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(lpthw) [sujx@zhangjiakou ~]$ tree projects/
projects/
└── skeleton
├── bin
├── docs
├── NAME
│   └── __init__.py
├── setup.py
└── tests
├── __init__.py
└── NAME_tests.py

5 directories, 4 files
(lpthw) [sujx@zhangjiakou projects]$ pwd
/home/sujx/projects
(lpthw) [sujx@zhangjiakou projects]$ nosetests

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK