python初学

基于《笨方法学Python 第四版》Zed Shaw著

1.print

  1. print “Hello World!”
  2. print ‘Hello World’
  3. print “I’d much rather you ‘not’.”
  4. print ‘I’d much rather you ‘‘not’’.’
    总结:1和2结果相同,全都输出Hello World
    3和4是内嵌另外两种引号的输出,注意内嵌不同引号的外面引号要不相同
    其中3的结果是输出 I’d much rather you ‘not’
    4的结果是输出I’d much rather you ‘‘not’’.

每一个print另起一行重新输入的时候会同时换行,也可以在同一个print的换行位置输入 \n 也可

2.注释与井号

3.数字和数学计算

print ("I will count the chicken")

print("Hen", 20+30) #显示 Hen 50
print('Rooster', 30+40) #显示 Rooster 70
#若是输入 Print("Hen",) 或者 print("Hen"),50 这两种都不会出错,结果都显示 Hen

print("I will count the eggs")
print (1+2+1/4+5%2+-5%3) #显示5.25
#区别:1/4的结果为0.25,-5%3的结果为1

print("Is it 3+2<5")
print(3+2<5)
#显示
#Is it 3+2<5
#False

print("Is it 3+2>=5")
print(3+2>=5)
#显示
#Is it 3+2>=5
#True

print("Is it 3+2<5",3+2<5)
#显示
#Is it 3+2<5 False

print("Is it 3+2>=5",3+2>=5)
#显示
#Is it 3+2>=5 True

4.变量和命名

total = 50
boys = 25
girls = total - boys
print("There are",total,"students in our class")
print(girls,"girls in it and", boys, "boys in it")

显示
There are 50 students in our class
25 girls in it and 25 boys in it

5.更多的变量打印

my_name = 'mcchan'
my_age = 21
my_height = 160
my_weight = 111.5
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'

print ("Let's talk about %s." %my_name) #切记,后引号后面不用加逗号
print ("She is %d years old." %my_age)
print ("She is %d centimeters tall." %my_height)
print ("She is %.1f grams heavy." %my_weight)
print ("She has %s eyes and %s teeth." %(my_eyes,my_teeth)) #两个连在一起的不能分开写

%r是一个万能格式化字符,什么都能打印出来

6.字符串和文本

Python 可以通过文本里的双引号 " 或者单引号 ’ 识别出字符串来

x = "There are %d types of people" %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)

print (x) #打印出变量x的内容
print (y) #打印出变量y的内容
print ("I said: %r." %x) #I said: 'There are 10 types of people'. said里面是单引号
print ('I also said: "%s".' % y) #I also said: "Those who know binary and those who don't.". said里面是双引号
hilarious = False
joke_evalution = "Isn't that joke so funny?! %r" #把%r换成%s也能得出正确结论

print (joke_evalution % hilarious) #Isn't that joke so funny?! False

w = "This is the left side of..."
e = "a string with a right side."
print(w + e) #This is the left side of...a string with a right side. 其中“+”并不是算术上的相加关系,而是字符串相拼接的关系

7.更多打印

print ("Mary had a little lab.")
print ("Its fleece was white as %s" %"snow")
print ("And everywhere that Mary went.")
print ("." *10) #作用是打印出10个相同的字符,..........

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

print (end1+end2+end3+end4+end5+end6,) #,没有作用
print (end7+end8+end9+end10+end11+end12)

8.打印?????

formatter = "%r %r %r %r"

print (formatter %(1,2,3,4))
print (formatter %("one", "two", "three", "four")) #'one' 'two' 'three' 'four', 因为formatter是双引号的字符串,内嵌的应该是单引号的字符串
print (formatter %(True, False , False, True))
print (formatter %(formatter, formatter, formatter, formatter)) #'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
print (formatter %(
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
))
 #打印出来的是单引号的三个字符串,其中第三个字符串是双引号的
 #'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

9.打印,打印

days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJune\nJuly\nAug\nSept\nOct\nNov\nDec\n"

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 line if we want, or 5, or 6.
""")
#其中,在打印之前有一行空白行,打印完毕之后有一个空白行

10.那是什么

转义字符的应用
在print语句块里面有单引号转义和双引号转义
(1)若是print(" “)里面的转义则应该是单引号转义,例如想要打印出双引号,则应该是”
(2)若是print(’ ‘)里面的转义则应该是双引号转义,例如想要打印出单引号’,则应该是’
\:打印出\

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)

想要打印出%d 10 效果
print ("%%d %d" %10)
其中第一个%d需要保留,而保留方式为%%d

11.提问

print ("How old are you ?")
age = input() #input()相当于键盘输入
print ("How tall are you ?")
height = input()
print ("How much do you weigh ?")
weight = input()

print ("So,you're %r old, %r tall, %r heavy" %(age, height, weight))

How old are you ?
21
How tall are you ?
160cm
How much do you weigh ?
111.5g
So,you’re ‘21’ old, ‘160cm’ tall, ‘111.5g’ heavy

12.提示别人

  • x = input("Name? ") #切记不要忘记引号,单引号和双引号均可
  • 作用是输出Name提示输入,并将输入赋值给变量x
# 相较于11的代码也可以这样改写
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh? ")

print ("So, you're %r old, %r tall, %r heavy." %(age, height, weight))

How old are you? 21
How tall are you? 160cm
How much do you weigh? 111.5g
So, you’re ‘21’ old, ‘160cm’ tall, ‘111.5g’ heavy.

13.参数、解包、变量

from sys import argv #import是将python的功能引入脚本,agrv是参数变量    把 sys 模组 import 进来也可以叫做库
script, first, second, third = argv #解包

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

The script id called: C:/Users/cmc and cxy/PycharmProjects/pythonProject1/main.py
Your first variable is: first
Your second variable is: second
Your third variable is third

PS C:\Users\cmc and cxy\PycharmProjects\pythonProject1> python main.py first 2nd 3rd #命令输入行
The script id called: main.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is 3rd

14.提示和传递

from sys import argv
scaipt, user_name = argv
prompt = '> '

print ("Hi %s, I'm the %s script." % (user_name, scaipt))
print ("I'd like to ask you a few questions.")

print ("Do you like me %s?" % user_name)
likes = input(prompt)
#将用户提示符设置为变量 prompt
#这样我们就不需要在每次用到 input 时重复输入提示用户的字符
#而且如果要将提示符修改成别的字串,只要改一个位置就可以了

print ("Where do you live %s?" %user_name)
lives = input(prompt)

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

print ("""
Alright, so you said %r about likeing me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer))
PS C:\Users\cmc and cxy\PycharmProjects\pythonProject1> python main.py mcchan
Hi mcchan, I'm the main.py script.
I'd like to ask you a few questions.
Do you like me mcchan?
> yes
Where do you live mcchan?
> China
What kind of computer do you have?
> HuiPu

Alright, so you said 'yes' about likeing me.
You live in 'China'. Not sure where that is.
And you have a 'HuiPu' computer. Nice.

15.读取文件

from sys import argv
script, filename = argv

txt = open(filename) #打开文件,它会接受一个参数,并且返回一个值

print("Here's your file %r:" % filename)
print(txt.read()) #读取文件
txt.close() #关闭文件

print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
txt_again.close()
PS C:\Users\cmc and cxy\PycharmProjects\pythonProject1> python main.py sample.txt
Here's your file '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:
> sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

16.读写文件

文件相关命令:

  • close – 关闭文件。跟你编辑器的 文件->保存… 一个意思。
  • read – 读取文件内容。你可以把结果赋给一个变量。
  • readline – 读取文本文件中的一行。
  • truncate – 清空文件,请小心使用该命令。
  • write(stuff) – 将 stuff 写入文件。
from sys import argv
script, filename = argv

print ("We're going to erase %r." % 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") #写入文件
#需要给 open 多赋予一个 'w' 参数, 因为 open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。
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: ")

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")

print ("And finally, we close it.")
target.close()
PS C:\Users\cmc and cxy\PycharmProjects\pythonProject1> python main.py sample.txt
We're going to erase 'sample.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: To all the people out there.
line 2: I say I don't like my hair.
line 3: I need to shave it off.
I'm going to write these to the file.
And finally, we close it.

17.更多文件操作

拷贝文件

from sys import argv
from os.path import exists
# import 使用了一个很好用的命令 exists,这个命令将文件名字符串作为参数,如果文件存在的话,它将返回 True,否则将返回 False。
script, from_file, to_file = argv

print ("Copying from %s to %s" % (from_file, to_file))

input_ = open(from_file)
indata = input_.read()

print ("The input file is %d bytes long" % len(indata)) #len是计算字节数

print ("Does the output file exist? %r" % exists(to_file))
print ("Ready, hit RETURN to continue, CTRL-C to abort.")
input()

output = open(to_file, "w")
output.write(indata)

print ("Alright, all done.")

output.close()
input_.close()

18.命名、变量、代码、函数

用def创建函数

def print_two(*args): #必须有冒号作为结尾,而参数放在括号里面
    arg1, arg2 = args #将参数解包
    print ("arg1: %r, arg2: %r" % (arg1, arg2))
#冒号以下,使用 4 个空格缩进的行都是属于 print_two 这个函数的内容
#因此函数定义的缩进内容会影响函数的定义
def print_two_again(arg1, arg2):
    print ("arg1: %r, arg2: %r" % (arg1, arg2))

def print_one(arg1):
    print ("arg1: %r" % arg1)

def print_none():
    print ("I got nothin'.")

print_two ("mc", "chan") 
#arg1: 'mc', arg2: 'chan'
#其中无论参数是使用单引号还是双引号的字符串,都会打印出带单引号的字符串
arg1: 'mc', arg2: 'chan'
print_two_again("mc", "chan")
print_one("First!")
print_none()

19.函数与变量

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print ("You have %d cheese!" % cheese_count)
    print ("You have %d boxes of 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) #混合参数传递

20.函数和文件

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 = current_line + 1
print_a_line(current_line, current_file)
#文件指针已经来到了第二行末尾第三行开始
#第三行
current_line = current_line + 1
print_a_line(current_line, current_file)

21.函数可以返回东西

return:

def add(a, b):
    print ("ADDING %d + %d" % (a, b))
    return a + b

def subtract(a, b):
    print ("SUBTRACTING %d - %d" % (a, b))
    return a-b

def multiply(a, b):
    print ("MULTIPLY %d * %d" % (a, b))
    return a * b

def divide(a, b):
    print ("DIVIDING %d / %d" % (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 ("Age: %d, Height: %d, Weight: %d, IQ: %d" %(age, height, weight, iq))

print ("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print ("That becomes:", what, "Can you do it by hand?")

22.自我回顾

23. 读代码

24. 更多练习

print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
\t The lovely world 
with logic so firmly planted #换行则为新的字符串
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none
"""

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

five = 10 - 2 + 3 - 6
print ("This should be five: %s" % 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) #与def的返回值一一对应

print ("With a starting point of: %d" % start_point)
print ("We'd have %d beeans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))

25.更多更多的练习???

def break_words(stuff):
    """This function will break up words for us""" #不用加print
    words = stuff.split(' ') #通过指定分隔符对字符串进行分割并返回一个列表
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words) #把参数words中的内容按照升序排列,并生成一个新的列表,然后返回函数的结果

def print_first_word(words):
    """Print the first word after popping it off."""
    word = words.pop(0) #拿出words列表中的第一个元素,并返回该元素的值,然后赋值给变量word
    print (word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1) #拿出words列表中的最后一个元素,并返回该元素的值,然后赋值给变量word
    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_and_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)

26.考试

  1. print(“How old are you?”, end=’ ') #end的含义
  2. print(f"So, you’re {age} old, {height} tall and {weight} heavy.") #括号的意思+f

27.记住逻辑关系

28.布尔表达式练习

29.如果(if)

people = 20
cats = 30
dogs = 15

if people < cats: #冒号一定要注意加上去
    print ("Too many cats! The world is doomed!") #凡是一个if冒号以下的缩进四个空格的就是该if里面的内容

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.")

30.else和if

people = 30
cars = 40
buses = 15

if cars > people:
    print ("We should take the cars.")
elif cars < people: #elif后面才可以加条件,而else之后不能加条件
    print ("We should not take the cars.")
else: #记得加冒号
    print ("We can't decide.")

if buses > cars:
    print ("That's too many buses.")
elif buses < cars:
    print ("Maybe we could take the buses.")
else:
    print ("We still can't decide.")

if people > buses:
    print ("Alright, let's just take the buses.")
else:
    print ("Fine, let's stay home then.")

31.作出决定

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 bear here eating a cheese cake. What do you do?")
    print ("1. Take the cake.")
    print ("2. Scream at the bear.")

    bear = input("> ")

    if bear == "1":
        print ("The bear eats 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. Bears runs away." % bear)

elif door == "2":
    print ("You stare into the endlees 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. Good job!")
    else:
        print ("The insanity rots yours eyes into a pool of muck. Good job!")

else:
    print ("You stumble around and fall on a knife and die. Good job!")

32. 循环和列表

创建列表

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

for number in the_count:   #for..in,number是每次循环的变量,初始值为列表首元素,in后面是列表名
    print ("This is count %d" % number)

for fruit in fruits:
    print ("A fruit of type: %s" % fruit)

for i in change:
    print ("I got %r" % i)

elements = []

for i in range(0, 6): #range函数,从0数到5,而不是数到6
    print ("Adding %d to the list." % i)
    elements.append(i) #变量追加到列表中

for i in elements:
    print ("Element was: %d" %i)
#也可以直接赋值elements = range(0,5)生成一个相同的列表

33.While循环

While循环可能会出现条件为永真式,为了避免这样的问题,需要遵循下面的规定:

  1. 尽量少用 while-loop,大部分时候 for-loop 是更好的选择。
  2. 重复检查 while 语句,确定条件布尔表达式最终会变成 False 。
  3. 如果不确定,就在 while-loop 的结尾打印出你要测试的值。看看它的变化。
i = 0
numbers = []

while i < 6:
    print ("At the top i is %d" % i)
    numbers.append(i) #将i作为numbers列表的元素追加进列表头位置
    i = i + 1
    print ("Numbers now: ", numbers) #并非一个一个元素来打印出列表元素,而是直接用numbers作为打印内容(没有用% numbers)
    print ("At the bottom i is %d" %i)
#前三次循环打印内容
#At the top i is 0
#Numbers now:  [0]
#At the bottom i is 1
#At the top i is 1
#Numbers now:  [0, 1]
#At the bottom i is 2
#At the top i is 2
#Numbers now:  [0, 1, 2]

print ("The numbers: ")

for num in numbers:
    print (num)

34.访问列表元素

访问列表第一个元素的操作:
animals = [‘bear’, ‘tiger’, ‘penguin’, ‘zebra’]
bear = animals[0]

35.分支和函数

from sys import exit #使用exit功能

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

    next = input("> ")
    if "0" in next or "1" in next: #如果next里面有0或者1
        how_much = int(next)
    else:
        dead("Man, lenrn 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 money.")
    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 = 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 = 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 = input("> ")

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

start()

36.设计与调试

37.复习各种符号

  1. 关键字

and、del、from、not、while、as、elif、global、or、with、assert、else、if、pass、yield、break、except、import、print、class、exec、in、raise、continue、finally、is、return、def、for、lambda、try

  1. 数据类型

True、False、None、strings、numbers、floats、lists

  1. 字符串转义序列
  • \
  • "
  • \a
  • \b
  • \f
  • \n
  • \r
  • \t
  • \v
  1. 字符串格式化
  • %d
  • %i
  • %o
  • %u
  • %x
  • %X
  • %e
  • %E
  • %f
  • %F
  • %g
  • %G
  • %c
  • %r
  • %s
  • %%
  1. 操作符号
  • **
  • /
  • //
  • %
  • <
  • <=
  • =

  • ==
  • !=
  • <>
  • ( )
  • [ ]
  • { }
  • @
  • ,
  • :
  • .
  • =
  • ;
  • +=
  • -=
  • *=
  • /=
  • //=
  • %=
  • **=

38.阅读代码

39.列表的操作

当看到像 mystuff.append(‘hello’) 这样的代码时,事实上已经在 Python 内部激发了一个连锁反应。以下是它的工作原理:

  1. Python 看到用到了 mystuff ,于是就去找到这个变量。也许它需要倒着检查看有没有在哪里用 = 创建过这个变量,或者检查它是不是一个函数参数,或者看它是不是一个全局变量。不管哪种方式,它得先找到 mystuff 这个变量才行。
  2. 一旦它找到了 mystuff ,就轮到处理句点 . (period) 这个操作符,而且开始查看 mystuff 内部的一些变量了。由于 mystuff 是一个列表,Python 知道mystuff 支持一些函数。
  3. 接下来轮到了处理 append 。Python 会将 “append” 和 mystuff 支持的所有函数的名称一一对比,如果确实其中有一个叫 append 的函数,那么 Python 就会去使用这个函数。
  4. 接下来 Python 看到了括号 ( (parenthesis) 并且意识到, “噢,原来这应该是一个函数”,到了这里,它就正常会调用这个函数了,不过这里的函数还要多一个参数才行。
  5. 这个额外的参数其实是…… mystuff! 很奇怪是不是?不过这就是Python 的工作原理,所以还是记住这一点,就当它是正常的好了。真正发生的事情其实是 append(mystuff, ‘hello’) ,不过看到的只是 mystuff.append(‘hello’) 。
ten_things = "Apples Oranges CrowsTelephone Light Sugar"

print("Wait there's not 10 things in that list, let's fix that.")

stuff = ten_things.split(' ') #字符串可以用split分裂操作,分裂出来为列表
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop() #列表可以用出表pop操作,弹出的为尾元素,若是添加进列表也是插进去尾元素
    print("Adding: ", next_one)
    stuff.append(next_one) #字符串、列表可以用追加操作append?
    print("There's %d items now." % len(stuff))

print("There we go: ", stuff)
#打印整个列表则是打印出中括号及其里面元素内容
#stuff =['Apples', 'Oranges', 'CrowsTelephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn', 'Frisbee']
print("Let's do some things with stuff.")
print(stuff[1]) #第二个元素
print(stuff[-1]) #尾元素
print(stuff.pop())
print(' *'.join(stuff)) #可对列表元素进行加入操作
#打印内容为: 将' *'分别插进去列表中除了首元素的其余所有元素之前,并不会打印出中括号
#Apples *Oranges *CrowsTelephone *Light *Sugar *Boy *Girl *Banana *Corn
print(stuff)
#其中列表并不会真正进行元素的加入操作,说明join操作对于列表元素并没有真正的影响
#['Apples', 'Oranges', 'CrowsTelephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
print('#'.join(stuff[3:5]))
#打印内容为将列表下标为3和5的元素即stuff[3]和stuff[5],中间用#隔开,并不会打印出中括号
#Light#Sugar

40.字典

Python 将这种数据类型叫做 “dict”,有的语言里它的名称是 “hash”。
列表的操作:

things = ['a', 'b', 'c', 'd']
print(things[1]) #b
things[1] = 'z'
print(things[1]) #z
print(things) #['a', 'z', 'c', 'd']

字典的操作:

stuff = {'name': 'MC', 'age': 36, 'height': 4 * 40}
print(stuff['name']) #MC
print(stuff['age']) #36
print(stuff['height']) #160
stuff['city'] = 'China'
print(stuff['city']) #China
print(stuff) #{'name': 'MC', 'age': 36, 'height': 160, 'city': 'China'}
stuff[1] = "HHH"
stuff[2] = "WWW"
print(stuff) #{'name': 'MC', 'age': 36, 'height': 160, 'city': 'China', 1: 'HHH', 2: 'WWW'}

删除关键字del:

stuff = {'name': 'MC', 'age': 36, 'height': 160, 'city': 'China', 1: 'HHH', 2: 'WWW'}
del stuff['city']
del stuff[1]
del stuff[2]
print(stuff) #{'name': 'MC', 'age': 36, 'height': 160}
cities = {'CA': 'China', 'MI': 'Detroit', 'FL': 'Jacksoncille'}

cities['NY'] = 'New Nork'
cities['OR'] = 'Portland'

def find_city(themap, state):
    if state in themap:
        return themap[state]
    else:
        return "Not Found"

cities['_find'] = find_city #将find_city函数的地址赋值

while True:
    print("State? (ENTER to quit)")
    state = input("> ")

    if not state: break

    city_found = cities['_find'](cities, state)
    print(city_found)

cities[’_find’] = find_city
city_found = cities[’_find’](cities, state)

一个函数也可以作为一个变量,def find_city 比如这一句创建了一个可以在任何地方都能使用的变量。在这段代码里,我们首先把函数find_city 放到叫做 cities 的字典中,并将其标记为 ‘_find’。 这和我们将州和市关联起来的代码做的事情一样,只不过我们在这里放了一个函数的名称。
所以一旦我们知道 find_city 是在字典中 _find 的位置,这就意味着我们可以去调用它。第二行代码可以分解成如下步骤:

  1. Python 看到 city_found = 于是知道了需要创建一个变量。
  2. 然后它读到 cities ,然后知道了它是一个字典
  3. 然后看到了 [’_find’] ,于是 Python 就从索引找到了字典 cities 中对应的位置,并且获取了该位置的内容。
  4. [’_find’] 这个位置的内容是我们的函数 find_city ,所以 Python 就知道了这里表示一个函数,于是当它碰到 ( 就开始了函数调用 )。
  5. cities, state 这两个参数将被传递到函数 find_city 中,然后这个函数就被运行了。
  6. find_city 接着从 cities 中寻找 states ,并且返回它找到的内容,如果什么都没找到,就返回一个信息说它什么都没找到。
  7. Python find_city 接受返回的信息,最后将该信息赋值给一开始的 city_found 这个变量。

41.来自Pearcal 25号行星的哥尔顿人(Gothons)

from sys import exit
from random import randint

def death():
    quips = ["You died. You kinda suck at this.",
             "Nice job, you died...jackass",
             "Such a luser."
             "I have a small puppy that's better at this."]
    print(quips[randint(0, len(quips)-1)]) #?
    exit(1)

def central_corridor():
    print("The Gotjons of Planet Percal #25 have invaded your ship and destroyed")
    print("You entire crew. You are the last surviving member and your last")
    print("mission os to get the neutron destruct bomb from the Weapons Armory,")
    print("put it in the bridge, and blow the ship up afterr getting into an ")
    print("escape pod.")
    print("\n")
    print("You're running down the central corridor to the Weapons Armory when")
    print("a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume")
    print("flowing around his hate filled body. He's blocking the door to the")
    print("Armory and about to pull a weapon to blast you.")

    action = input("> ")
    if action == "shoot!":
        print("Quick on the draw you yank out your blaster and fire it at the Gothon.")
        print("His clown costume is flowing and moving around his body, which throws")
        print("completely ruins his brand new costume his mother bought him, which")
        print("makes him fly into an insane rage and blast you repeatedly in the face until")
        print("you are dead. Then he eats you.")
        return 'death'

    elif action == "dodge!":
        print("Like a world class boxes you dodge, weave, slip and slide right")
        print("as the Gothon's blaster cranks a laser past your head.")
        print("In the middle of your artful dodge your foot slips and you")
        print("bang your head on the metal wall and pass out.")
        print("You wake up shortly after only to die as the Gothon stomps on")
        print("your head and eats you.")
        return 'death'

    elif action == "tell a joke":
        print("Lucky for you they made you learn Gothon insults in the academy.")
        print("You tell the one Gothon joke you know:")
        print("Lbhe zvgure vf fb sng, jura fur fvgf nebhap gur ubhfr, fur fvgf nebhaq gur ubhfr.")
        print("The Gothon stops, tries not to laugh, then bursts out laughing and can't move.")
        print("While he's laughing you run up and shoot him square in the head")
        print("putting him down, then jump through the Weapon Armory door.")
        return 'laser_weapom_armory'

    else:
        print("DOES NOT COMPUTE!")
        return 'central_corridor'

def laser_weapon_armory():
    print("You do a dic=ve roll into the Weapon Armory, crouch and scan the room")
    print("for more Gothon that might be hiding. It's dead quiet, too quiet.")
    print("You stand up and run to the far side of the room and find the")
    print("netron bomb in its container. There's a keypad lock on the box")
    print("and you need the code to get the bbomb out. If you get the code")
    print("wrong 10 times then the lock closrs forever and you can't")
    print("get the bomb. The code is 3 digits.")
    code = "%d%d%d" % (randint(1, 9), randint(1, 9), randint(1,9)) #赋值的新方式
    guess = input("[keypad]> ")
    guesses = 0

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

    if guess == code:
        print("The container clicksopen and the seal breaks, letting gas out.")
        print("You grab the neutron bomb and run as fast as you can to the")
        print("bridge where you must place it in the right spot")
        return 'the_bridge'

    else:
        print("The lock buzzrs one last time and then you hear a sickening")
        print("melting sound as the mechanism is fused together.")
        print("You decide to sit there, and finally the Gothons blow up the")
        print("ship from their ship and you die.")
        return 'death'

def the_bridge():
    print("You burst onto the Bridge with the neutron destruct bomb")
    print("under your arm and surprise 5Gothons who are trying to")
    print("take control of the ship. Each of them has an even uglier")
    print("clown costume than the last. They haven't pulled their")
    print("weapons out yet, as they see the active bomb under your")
    print("arm and don't want to set it off.")

    action = input("> ")

    if action == "throw the bomb":
        print("In a panic you throw the bomb at the group of Gothons")
        print("and make a leap for for the door. Right as you drop it a")
        print("Gothon shoots you right in the back killing you.")
        print("As you die you see another Gothon frantcally try to disarm")
        print("the bomb. You die knowing they will probably blow up when")
        print("it goes off.")
        return 'death'

    elif action == "slowly place the bomb":
        print("You point your blaster at the bomb under your arm")
        print("and the Gothons put their hands up and start to sweat.")
        print("You inch backward to the door, open it, and then carefully")
        print("place the bomb on the floor, pointing your blaster at it.")
        print("You then jump back through the door, punch the close button")
        print("and blast the lock so the Gothons can't get out.")
        print("Now that the bomb is placed you run to the escape pod to")
        print("get off this tin can.")
        return 'escape_pod'

    else:
        print("DOES NOT COMPUTE!")
        return 'the_bridge'

def escape_pod():
    print("You rush through the ship desperately reying to make it to")
    print("the escape pod before the whole ship explodes. It seems like")
    print("hardly any Gothons are on the shiip, so your run is clear of")
    print("interference. You get to the chamber with the escape pods, and")
    print("now need to pick one to take. Some of them could be damaged")
    print("but you don't have time to look, There's 5 pods, which one")
    print("do you take?")

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

    if int(guess) != good_pod:
        print("You jump into pod %s and hit the eject button." % guess)
        print("The pod escapes out into the void of space, then")
        print("implodes as the hull ruptures, crushing your body")
        print("into jam jelly.")
        return 'death'
    else:
        print("You jump into pod %s and hit the eject button." % guess)
        print("The pod easily slides out into space heading to")
        print("the planet below. As it flies to the planet, you look")
        print("back and see your ship implode then explode like a")
        print("bright star, taking out the Gothon ship at the same")
        print("time. You won!")
        exit(0)

ROOMS = {
    'death': death,
    'central_corridor': central_corridor,
    'laser_weapon_armory': laser_weapon_armory,
    'the_bridge': the_bridge,
    'escape_pod': escape_pod
}

def runner(map, start):
    next = start
    while True:
        room = map[next]
        print("\n--------")
        next = room()

runner(ROOMS, 'central_corridor')

42.物以类聚?

用到“class”的编程语言被称作“Object Oriented Programming(面向对象编程)”语言。

class TheThing(object):
    def __init__(self):
        self.number = 0

    def some_fuction(self):
        print("I got called.")

    def add_me_up(self, more):
        self.number += more
        return self.number

a = TheThing()
b = TheThing()

a.some_fuction()
b.some_fuction()

print(a.add_me_up(20))
print(a.add_me_up(20))
print(b.add_me_up(30))
print(b.add_me_up(30))

print(a.number)
print(b.number)

self是Python创建的额外一个参数
有了参数self才能实现 a.some_function()这种用法,这时它就会把前者翻译成 some_function(a) 执行下去

为什么用 self 呢?
因为函数并不知道这个“实例”是来自叫 TheThing 或者别的名字的class。所以你只要使用一个通用的名字 self 。这样你写出来的函数就会在任何情况下都能正常工作。

__init__函数:为 Python class 设置内部变量的方式
可以使用 . 将它们设置到self上面

from sys import exit
from random import randint

class Game(object):

    def __init__(self, start):
        self.quips = [
            "You died. You kinda suck at this.",
            "Your mom would be proud. If she were smarter.",
            "Such a luser.",
            "I have a small puppy that's better at this."
        ]

        self.start = start

    def play(self):
        next = self.start

        while True:
            print("\n-------")
            room = getattrr(self, next) #有问题
            next = room()

    def death(self):
        print(self.quips[randint(0, len(self.quips) - 1)])
        exit(1)

    def central_corridor():
        print("The Gotjons of Planet Percal #25 have invaded your ship and destroyed")
        print("You entire crew. You are the last surviving member and your last")
        print("mission os to get the neutron destruct bomb from the Weapons Armory,")
        print("put it in the bridge, and blow the ship up afterr getting into an ")
        print("escape pod.")
        print("\n")
        print("You're running down the central corridor to the Weapons Armory when")
        print("a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume")
        print("flowing around his hate filled body. He's blocking the door to the")
        print("Armory and about to pull a weapon to blast you.")

        action = input("> ")
        if action == "shoot!":
            print("Quick on the draw you yank out your blaster and fire it at the Gothon.")
            print("His clown costume is flowing and moving around his body, which throws")
            print("completely ruins his brand new costume his mother bought him, which")
            print("makes him fly into an insane rage and blast you repeatedly in the face until")
            print("you are dead. Then he eats you.")
            return 'death'

        elif action == "dodge!":
            print("Like a world class boxes you dodge, weave, slip and slide right")
            print("as the Gothon's blaster cranks a laser past your head.")
            print("In the middle of your artful dodge your foot slips and you")
            print("bang your head on the metal wall and pass out.")
            print("You wake up shortly after only to die as the Gothon stomps on")
            print("your head and eats you.")
            return 'death'

        elif action == "tell a joke":
            print("Lucky for you they made you learn Gothon insults in the academy.")
            print("You tell the one Gothon joke you know:")
            print("Lbhe zvgure vf fb sng, jura fur fvgf nebhap gur ubhfr, fur fvgf nebhaq gur ubhfr.")
            print("The Gothon stops, tries not to laugh, then bursts out laughing and can't move.")
            print("While he's laughing you run up and shoot him square in the head")
            print("putting him down, then jump through the Weapon Armory door.")
            return 'laser_weapom_armory'

        else:
            print("DOES NOT COMPUTE!")
            return 'central_corridor'

    def laser_weapon_armory():
        print("You do a dic=ve roll into the Weapon Armory, crouch and scan the room")
        print("for more Gothon that might be hiding. It's dead quiet, too quiet.")
        print("You stand up and run to the far side of the room and find the")
        print("netron bomb in its container. There's a keypad lock on the box")
        print("and you need the code to get the bbomb out. If you get the code")
        print("wrong 10 times then the lock closrs forever and you can't")
        print("get the bomb. The code is 3 digits.")
        code = "%d%d%d" % (randint(1, 9), randint(1, 9), randint(1, 9))  # 赋值的新方式
        guess = input("[keypad]> ")
        guesses = 0

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

        if guess == code:
            print("The container clicksopen and the seal breaks, letting gas out.")
            print("You grab the neutron bomb and run as fast as you can to the")
            print("bridge where you must place it in the right spot")
            return 'the_bridge'

        else:
            print("The lock buzzrs one last time and then you hear a sickening")
            print("melting sound as the mechanism is fused together.")
            print("You decide to sit there, and finally the Gothons blow up the")
            print("ship from their ship and you die.")
            return 'death'

    def the_bridge():
        print("You burst onto the Bridge with the neutron destruct bomb")
        print("under your arm and surprise 5Gothons who are trying to")
        print("take control of the ship. Each of them has an even uglier")
        print("clown costume than the last. They haven't pulled their")
        print("weapons out yet, as they see the active bomb under your")
        print("arm and don't want to set it off.")

        action = input("> ")

        if action == "throw the bomb":
            print("In a panic you throw the bomb at the group of Gothons")
            print("and make a leap for for the door. Right as you drop it a")
            print("Gothon shoots you right in the back killing you.")
            print("As you die you see another Gothon frantcally try to disarm")
            print("the bomb. You die knowing they will probably blow up when")
            print("it goes off.")
            return 'death'

        elif action == "slowly place the bomb":
            print("You point your blaster at the bomb under your arm")
            print("and the Gothons put their hands up and start to sweat.")
            print("You inch backward to the door, open it, and then carefully")
            print("place the bomb on the floor, pointing your blaster at it.")
            print("You then jump back through the door, punch the close button")
            print("and blast the lock so the Gothons can't get out.")
            print("Now that the bomb is placed you run to the escape pod to")
            print("get off this tin can.")
            return 'escape_pod'

        else:
            print("DOES NOT COMPUTE!")
            return 'the_bridge'

    def escape_pod():
        print("You rush through the ship desperately reying to make it to")
        print("the escape pod before the whole ship explodes. It seems like")
        print("hardly any Gothons are on the shiip, so your run is clear of")
        print("interference. You get to the chamber with the escape pods, and")
        print("now need to pick one to take. Some of them could be damaged")
        print("but you don't have time to look, There's 5 pods, which one")
        print("do you take?")

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

        if int(guess) != good_pod:
            print("You jump into pod %s and hit the eject button." % guess)
            print("The pod escapes out into the void of space, then")
            print("implodes as the hull ruptures, crushing your body")
            print("into jam jelly.")
            return 'death'
        else:
            print("You jump into pod %s and hit the eject button." % guess)
            print("The pod easily slides out into space heading to")
            print("the planet below. As it flies to the planet, you look")
            print("back and see your ship implode then explode like a")
            print("bright star, taking out the Gothon ship at the same")
            print("time. You won!")
            exit(0)

a_game = Game("central_corridor")
a_game.play() #有问题

43.制作一个游戏

44.游戏评分

将 class (类)里边的函数称作 method (方法)

45.对象、类、以及从属关系

类:class
对象:object

class Animal(object):
    pass #??

class Dog(Animal):
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init__(self, name):
        self.name = name

class Person(object):
    def __init__(self, name):
        self.name = name

        self.pet = None

class Employee(Person):
    def __init__(self, name, salary):
        super(Employee, self).__init__(name) #??
        self.salary = salary

class Fish(object):
    pass

class Salmon(Fish):
    pass

class Halibut(Fish):
    pass

rover = Dog("Rover")

satan = Cat("Satan")

mary = Person("Mary")

mary.pet = satan

frank = Employee("Frank", 120000)

frank.pet = rover

flipper = Fish()

crouse = Salmon()

harry = Halibut()

46.项目骨架

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值