《Learn Python the Hard Way》笔记-1序言&&2前言&&3简介
https://github.com/521xueweihan/python3 简介读和写、注重细节、发现不同exercise0.安装和准备略,网上很多。我是用anaconda安装的。我这里是python3.所以不要被我误导。出现问题后排查,1、中英文符号;2、python2与python3差异;3、.py是文件,不能再pyth...
https://github.com/521xueweihan/python
3 简介
读和写、 注重细节、 发现不同
exercise0.安装和准备
略,网上很多。我是用anaconda安装的。我这里是python3.所以不要被我误导。
出现问题后排查,1、中英文符号;2、python2与python3差异;3、.py是文件,不能再python中调用。4、文件的路径。
print ("Hello World!")
print ("Hello Again")
print ("I like typing this.")
print ("This is fun.")
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
exercise2. 注释和”#“
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code;
# print "This won't run."
print("This will run.")
exercise3. 数字和数学计算
- + plus 加号
- - minus 减号
- / slash 斜杠 除法
- * asterisk 星号 乘法
- % percent 百分号 模除
- < less-than 小于号
- > greater-than 大于号
- <= less-than-equal 小于等于号
- >= greater-than-equal 大于等于号
print("I will now count my chickens:")
print("Hens",25+30/6)
print("Roosters",100-25*3%4)
print("Now I will count the eges:")
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 greater or equal?",5>=-2)
print("Is it less or equal?",5<=-2)
exercise4. 变量和命名
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.")
exercise5. 更多的变量和打印
my_name = 'Zed A.Shaw'
my_age = 35 #not a lie
my_height = 74 #include
my_weight = 180 #lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print('Let\'s talk about %s .'%(my_name))
print('He\'s %d inches tall.'%(my_height))
print('He\'s %d pounds heavy.')
print('Actually that\'s not too heavy.')
print('He\'s got %s eyes and %s hair.'%(my_eyes,my_hair))
print('His teeth are usually %s depending on the coffee.'%(my_teeth))
#this line is tricky, try to get it exactly right
print('If I add %d, %d, and %d I get %d.'%(my_age, my_height, my_weight, my_age + my_height+ my_weight))
round()生成浮点数。
exercise6. 字符串和文本
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)
print(y)
print("I said:%r."%(x))
print("I also said: '%s'."%(y))
hilarious = False
joke_evaluation = "Isn's that joke so funny?! %r"
print(joke_evaluation % hilarious)
w = "This is the left side of ..."
e = "a string with a right side."
print( w + e)
%r表示变量的”原始“数据值,也就是字符串会自动加上单引号。
exercise7.更多的打印(输出)
print("Mary had a little lamb.")
print("Its fleece was white as %s ."%('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)
, end=" "表示输出不回车。
exercise8. 打印,打印,打印
formatter = "%r %r %r %r"
print(formatter%(1,2,3,4))
print(formatter%("one","two","three","four"))
print(formatter%(True,False,False,True))
print(formatter%(formatter,formatter,formatter,formatter))
print(formatter%(
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
))
exercise9. 打印,打印,打印
#Here's some new strange stuff, remember type it exactly
days = "Mon Tue Wed Thu Fir 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.
""")
"""3个双引号可以将段落直接组织在一起。中间不能有空格
%r输入任何值输出任何值。
exercise10.那是什么
/(back-slash)转义字符
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)
转义字符 | 实现功能 |
\ | Backslash() |
\' | Single-quote(') |
\" | Double-quote(") |
\a | ASCll bell(BEL) |
\b | ASCll backspace(BS) |
\f | ASCll formfeed(FF) |
\n | ASCll linefeed(LF) |
\N{name} | Character named name in the Unicode database(Unicode only) |
\r ASCll | Carriage Return(CR) |
\t ASCll | Horizontal Tab(TAB) |
\uxxxx | Character with 16-bit hex value xxx(Unicode only) |
\Uxxxxxxxx | Character with 32-bit hex value xxxxxxxx(Unicode only) |
\v | ASCll vertical tab(VT) |
\ooo | Character with octal value ooo |
\xhh | Character with hex value hh |
exercise11.提问
print ("How old are you", end=" ")
age = input()
print("How tall are you?",end="")
height=input()
print("How much do you weigh?",end=" ")
weight = input()
print ("So, you're %r old, %r tall and %r heavy."%(age,height,weight))
x=int(input())将字符串转成整数。
execise12.提示别人
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 and %r heavy."%(age,height,weight))
python -m pydoc input 帮助
exercise13.参数,解包,变量
from sys import argv
script, first, second, third = argv
print("The script is called:",script)
print("Your first variable is:",first)
print("Your second variable is:",second)
print("Your third variable is:",third)
exercise14. 提示和传递
from sys import argv
script, user_name = argv
prompt = '> '
print("Hi %s, I'm the %s script."%(user_name, script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?"%(user_name))
likes = input(prompt)
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 liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
"""%(likes, lives, computer))
"""定义多行字符串,%字符串格式化工具
exercise15.读文件
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.
from sys import argv
script, filename = argv
txt = open(filename)
print("Here's your file %r:"%(filename))
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
exercise16.读写文件
- close -- 关闭文件。类似于编辑器 文件->保存。
- read -- 读取文件内容。将结果赋值给一个变量。
- readlin -- 读取文本文件中的一行。
- truncate --清空文件,慎用
- write('stuff') -- 将stuff写入文件
write需要接收一个字符串作为参数。
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')
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()
'w'以写的方式打开,'r'只读,'a'追加
'w+','r+','a+'同时以读写模式打开文件
exercise17.更多文件操作
import导入的exists判断文件是否存在
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print("Copying from %s to %s"%(from_file,to_file))
#we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
print("The input file is %d bytes long"%(len(indata)))
print("Does the output file exist? %r"%(exists(to_file)))
print("Readly, hit 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()
indata = open(from_file).read()当执行完这一行之后文件自动关闭。
exercise18.命名,变量,代码,函数
- 给代码片段命名,就和“变量”给字符串和数字命名一样。
- 可以接受参数,就和较笨接受argv一样
- 通过使用#1和#2可以让你创建“微型脚本”或者“小命令”
使用def新建函数。
#this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print("arg1: %r, arg2: %r"%(arg1, arg2))
#ok, that *args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
print("arg1 : %r ,arg2: %r"%(arg1,arg2))
#this just takes one argument
def print_one(arg1):
print("arg1: %r"%(arg1))
#this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First:")
print_none()
- def后面跟函数名称,最好能体现函数的功能。
- *args,和脚本argv非常相似,参数必须放在圆括号()中才能正常工作
- 冒号:结束本行,然后开始下一行缩进。
- 冒号一下使用4个控股个缩进的行都是这个函数的内容,其中第一行是将参数解包,这和脚本参数解包原理差不多。
- 打印
函数名和变量命名规则一致,不能以数字开头,只能包含字母数字、下划线。
argv是脚本,*args,都是高速参数组织成一个列表放在args中。
exercise19.函数和变量
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 cbmbine the tow, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers+1000)
exercise20. 函数和文件
from sys import argv
script, input_file = argv
#input_file="D:/WorkSpace/Code/Python/test.txt"
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)
0
f.seek(0)就靠近文件的开头一点。每次执行f.readline()就从文件中读取一行内容。
\n换行符。
readline()返回一行就会以\n结尾的文件内容
seek(0)重新定位在文件的第0位,第一个字节处
exercise21.函数的返回值
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("MULTIPLYING %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 function!")
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))
# A pussle for the extra credit, type it in anyway.
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?")
exercise22.到目前为止你学到了什么?
exercise23.阅读代码
- github.com
- launchpad.com
- gitorious.org
- sourceforge.net
exercise24.更多的练习
print("Let's practice everything.")
print("You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.")
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comperhend passion from intuition
and requires an explanation
\n\t\t where 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)
print("With a starting point of:%d"%(start_point))
print("We'd have %d beans, %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)))
exercise25.更多更多的练习
启动python解析器
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_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)
如果function出现错误的话,需要重启python解析器,再次运行程序。
使用help(ex25)
help(ex25.break_words)
定义函数是放在""""""之间的东西是模块的帮助文档,documentation comments(文档注释)
from ex25 import *导入模组
exercise26. 恭喜你,可以进行一次考试了
http://learnpythonthehardway.org/book/exercise26.txt
命名为ex26.py
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.poop(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_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)
print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do \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
and requires an explantion
\n\t\twhere there is none.
"""
print("--------------")
print(poem)
print("--------------")
five = 10 - 2 + 3 - 5
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)
print("With a starting point of: %d" % start_point)
print("We'd have %d jeans, %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 crabapples." % secret_formula(start_point))
import ex25
sentence = "All god\tthings come to those who weight."
words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)
ex25.print_first_word(words)
ex25.print_last_word(words)
ex25.print_first_word(sorted_words)
ex25.print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print (sorted_words)
ex25.print_first_and_last(sentence)
ex25.print_first_and_last_sorted(sentence)
exercise27.记住逻辑
逻辑术语
- and 与
- or 或
- not 非
- !=(not equal)不等于
- ==(equal)等于
- >=(greater-than-equal)大于等于
- <=(less-than-equal)小于等于
- True 真
- False假
真假表...
exercise28.布尔表达式
True and True
False and True
1 == 1 and 2 == 1
"test" == "test"
1 == 1 or 2 != 1
True and 1 == 1
False and 0 != 0
True or 1 == 1
"test" == "testing"
1 != 0 and 2 == 1
"test" != "testing"
"test" == 1
not (True and False)
not (1 == 1 and 0 != 1)
not (10 == 1 or 1000 == 1000)
not (1 != 10 or 3 == 4)
not ("testing" == "testing" and "Zed" == "Cool Guy")
1 == 1 and (not ("testing" == 1 or 1 == 0))
"chunky" == "bacon" and (not (3 == 4 or 3 == 3))
3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))
exercise29. IF语句
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.")
注意缩进
exercise30. Else 和if
冒号“:”告诉python要创建一个新的代码块,缩进4个空格,标志这些代码属于这个代码块。
people = 30
cars = 40
trucks = 15
if cars > people:
print( "We should take the cars.")
elif cars < people:
print( "We should not take the cars.")
else:
print ("We can't decide.")
if trucks > cars:
print( "That's too many trucks.")
elif trucks < cars:
print ("Maybe we could take the trucks.")
else:
print ("We still can't decide.")
if people > trucks:
print ("Alright, let's just take the trucks.")
else:
print( "Fine, let's stay home then.")
elif块
exercise31.做出决定
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. Bear runs away." % (bear))
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. Good job!")
else:
print ("The insanity rots your eyes into a pool of muck. Good job!")
else:
print ("You stumble around and fall on a knife and die. Good job!")
注意缩进
elif的使用
在范围内0<x<10或者x in range(0,10)
exercise32.循环和列表
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print("This is count %d"%(number))
# same as above
for fruit in fruits:
print("A fruit of type: %s"%(fruit))
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print("I got %r"%(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("Adding %d to the list."%(i))
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print("Element was: %d"%(i))
range()
for循环使用一个没有定义过的变量,因为循环开始就定义了。
range()不包含最后一个元素
append()在列表末尾追加一个元素
exercise33.while循环
i = 0
numbers = []
while i<6:
print ("At the top i is %d "% (i))
numbers.append(i)
i = i + 1
print ("Numbers now ", numbers)
print ("At the bottom i is %d "% (i))
print ("The numbers:" )
for num in numbers:
print (num)
CTRL 再敲 c可以暂停程序
execise34.访问列表元素
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
animals[0]
exercise35.分支和函数
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 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. 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("Your 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()
exit(0)来中止程序。
exit(1)退出程序出现错误。
exit(0)正常退出
exercise36.设计和调试
exercise37.复习符号
关键字
KEYWORD | DESCRIPTION | EXAMPLE |
---|---|---|
and | 逻辑与 | True and False == False |
as | with-as语句的一部分 | with X as Y: pass |
assert | 声明 | assert False, "Error! |
break | 停止整个循环 | while True: break |
class | 定义一个类 | class Person(object) |
continue | 停止这一次循环,但继续下一次循环 | while True: continue v |
def | 定义一个函数 | def x(): pass |
del | 从字典中删除 | del X[Y] |
elif | Else if 条件 | if: X; elif: Y; else: 3 |
else | Else条件 | if: X; elif: Y; else 3 |
except | 如果捕获异常,执行该代码块 | except ValueError, e: print e |
exec | 将字符串作为Python代码执行 | exec 'print "hello"' |
finally | 不管是否有一场,finally代码块都执行 | finally: pass |
for | for循环 | for X in Y: pass |
from | 从某一模块中引入特定部分 | import X in Y: pass |
global | 定义一个全局变量 | global x |
if | If条件 | if: X; elif: Y; else: 3 |
import | 引入一个模块到当前模块 | import os |
in | for循环的一部分/测试X in Y。 | for X in Y: pass / 1 in[1] == True |
is | 类似==判断是否相等 | i is 1 == True |
lambda | 创建一个无名函数 | s = lambda y: y ** y; s(3) |
not | 逻辑非 | not True == False |
or | 逻辑或 | True or False == True |
pass | 该代码块为空 | def empty(): pass |
打印一个字符串 | print 'this string' | |
raise | 代码出错时,跑出一个异常 | raise ValueError("No") |
return | 退出函数并返回一个返回值 | def X(): return Y |
try | 尝试代签代码块,有异常则进入except代码块 | try: pass |
while | While循环 | while X: pass |
with | 一个变量的别名 | with X as Y: pass |
yield | 暂停,返回给调用者 | def X(): yield Y; X().next() |
数据类型
TYPE | DESCRIPTION | EXAMPLE |
---|---|---|
True | True布尔值 | True or False == True |
False | False布尔型 | False and True == False |
None | 表示“nothing”或者"no value". | x = None |
string | 字符串,存储文本信息 | x = "hello" |
numbers | 储存整数 | i = 100 |
floats | 储存小数 | i = 10.389 |
lists | 储存某种东西的列表 | j = [1, 2, 3, 4] |
dicts | 储存某些东西的键值对 | e ={'x': 1, 'y': 2} |
字符串转义序列
ESCAPE | DESCRIPTION |
---|---|
\\ | 斜线 |
\' | 单引号 |
\“ | 双引号 |
\a | Bell |
\b | 退格 |
\f | Formfeed |
\n | 换行 |
\r | Carriage |
\t | Tab键 |
\v | 垂直的tab |
字符串格式化
ESCAPE | DESCRIPTION | EXAMPLE |
---|---|---|
%d | 格式化整数(不包含浮点数) | "%d" % 45 == '45' |
%i | 与%d相同 | “%i” % 45 == '45' |
%o | 8进制数字 | "%o" % 1000 == '1750' |
%u | 负数 | "%u" % -1000 = '-1000' |
%x | 小写的十六进制数字 | "%x" % 1000 =="3e8" |
%X | 大写的十六进制数字 | "%X" % 1000 =="3E8" |
%e | 小写的'e'的指数标记 | "%e" % 1000 == '1.000000e+03' |
%E | 大写的'E'的指数标记 | "%E" % 1000 == '1.000000e+03' |
%f | 浮点数 | "%f" % 10.34 ==' 1.000000e+03' |
%F | 与%f相同 | “%F” % 10.34 ==‘1.000000e+03’ |
%g | %f或者%e中较短的一个 | "%g" % 10.34 == '10.34' |
%G | %F或者%E中较短的一个 | "%G" % 10.34 == '10.34' |
%c | 字符格式化 | "%c" % 34 =="'' |
%r | 类型格式化 | "%r" % int == "<type 'int'>" |
%s | 字符串格式化 | "%s there" % 'hi' == 'hi there' |
%% | 表示百分号% | "%g%%" % 10.34 == '10.34%' |
操作符
OPERATOR | DESCRIPTION | EXAMPLE |
---|---|---|
+ | 加 | 2 + 4 ==6 |
- | 减 | 2 - 4 == -2 |
* | 乘法 | 2 * 4 == 8 |
** | 幂乘 | 2 ** 4 == 16 |
/ | 除 | 2 / 4.0 ==0.5 |
// | 整除,得到除法的商。 | 2 // 4.0 == 0.0 |
% | 模除,返回除法的余数。 | 2 % 4 == 2 |
< | 小于 | 4 < 4 == False |
> | 大于 | 4 > 4 == False |
<= | 小于等于 | 4 <= 4 == True |
>= | 大于等于 | 4 >= 4 == True |
== | 等于,比较操作对象是否相等。 | 4 == 5 == False |
!= | 不等于 | 4 != 5 == True |
<> | 不等于 | 4 <> 5 =True |
() | 括号 | len('hi') == 2 |
[] | 列表括号 | [1, 3, 4] |
{} | 字典括号 | {'x': 5, 'y': 10} |
@ | 装饰符 | @classmethod |
, | 逗号 | range(0,10) |
: | 冒号 | def x(): |
. | Dot | self.x = 10 |
= | 赋值等于 | x = 10 |
; | 分号 | print "hi"; print "there" |
+= | 加等于 | x = 1; x += 2 |
-= | 减等于 | x = 1; x -= 2 |
*= | 乘等于 | x = 1; x *= 2 |
/= | 除等于 | x = 1; x /= 2 |
//= | 整除等于 | x = 1; x //= 2 |
%= | 模除等于 | x = 1; x %= 2 |
**= | 幂乘等于 | x = 1; x **= 2 |
exercise38. 列表操作
列表追加append
class Thing(object):
def test(self,hi):
print(hi)
a = Thing()
a.test("hello")
注意test中加入的self参数
ten_things = "Apples Oranges 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("There are %d items now."%(len(stuff)))
print("There we go:",stuff)
print(stuff[1])
print(stuff[-1]) # whoa! fancy
print(stuff.pop())
print(' '.join(stuff))# what? cool!
print('#'.join(stuff[3:5]))# super stellar!
object oriented Programming :OOP
' '.join(stuff)使用一个字符串将列表内容链接起来
exercise39.字典,可爱的字典
字典(dictionary)
python将这种数据类型叫做"dict",其他语言里面是“hash”
修改
添加
删除
映射是字典里的关键概念
# 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': 'Jacksonville'
}
# add some more city
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print('-' * 10)
print('NY State has: ', cities['NY'])
print('OR State has: ', cities['OR'])
# print 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 cities.items():
print("%s is abbreviated %s"%(abbrev, state))
# print every city in state
print('-' * 10)
for abbrev, city, in cities.items():
print("%s has the city %s"%(abbrev, city))
# now do both at the same time
print('-' * 10)
for state, abbrev in states.items():
print("%s state is abbreviated %s and has city %s"%(state, abbrev, 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.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print("The city for the state 'TX' is: %s"%(city))
hashmap.py
def new(num_buckets = 256):
"""Initializes a Map with the given number of buckets."""
aMap = []
for i in range(0, num_buckets):
aMap.append([])
return aMap
def hash_key(aMap, key):
"""Given a key this will create a number and then convert it to
an index for the aMap's buckets."""
return hash(key) % len(aMap)
def get_bucket(aMap, key):
"""Given a key, find the bucket where it would go."""
bucket_id = hash_key(aMap, key)
return aMap[bucket_id]
def get_slot(aMap, key, default=None):
"""
Returns the index, key, and value of a slot found in a bucket.
Returns -1, key, and default (None if not set) when not found.
"""
bucket = get_bucket(aMap, key)
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
return i, k, v
return -1, key, default
def get(aMap, key, default=None):
"""Gets the value in a bucket for the given key, or the default."""
i, k, v = get_slot(aMap, key, default = default)
return v
def set(aMap, key, value):
"""Sets the key to the value, replacing any existing value."""
bucket = get_bucket(aMap, key)
i, k, v = get_slot(aMap, key)
if i>= 0:
# the key exists, replace it
bucket[i] = (key, value)
else:
# the key does not, append to create it
bucket.append((key, value))
def delete(aMap, key):
"""Deletes the given key from the Map."""
bucket = get_bucket(aMap, key)
for i in xrange(len(bucket)):
k, v =bucket[i]
if key == k:
del bucket[i]
break
def list(aMap):
"""Prints out what's in the Map."""
for bucket in aMap:
if bucket:
for k, v in bucket:
print (k, v)
ex39_test.py
import hashmap
# create a mapping of state to abbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')
# create a basic set of states and some cities in them
cities = hashmap.new()
hashmap.set(cities, 'CA', 'San Francisco')
hashmap.set(cities, 'MI', 'Detroit')
hashmap.set(cities, 'FL', 'Jacksonville')
# add some more cities
hashmap.set(cities, 'NY', 'New York')
hashmap.set(cities, 'OR', 'Portland')
# print out some cities
print('-' * 10)
print("NY State has: %s"%(hashmap.get(cities, 'NY')))
print("OR State has: %s"%(hashmap.get(cities, 'OR')))
# print some states
print('-' * 10)
print("Michigan's abbreviation is: %s"%(hashmap.get(states, 'Michigan')))
print("Florida has: %s"%(hashmap.get(states, 'Florida')))
# do it by using the state then cities dict
print("-" * 10)
print("Michigan has: %s"%(hashmap.get(cities, hashmap.get(states,'Michigan'))))
print("Florida has: %s"%(hashmap.get(cities, hashmap.get(states, 'Florida'))))
# prinr every state abbreviation
print("-" * 10)
hashmap.list(states)
# print every city in state
print("-" * 10)
hashmap.list(cities)
print('-' * 10)
state = hashmap.get(states, 'Texas')
if not state:
print("Sorry, no Texas.")
# default values using ||= with the nil result
# can you do this on one line?
city = hashmap.get(cities, 'TX', 'Does Not Exist')
print("The city for the state 'TX' is %s"%(city))
set有的话替换,没有的话新增
new初始化num_buckets大小的hashmap
hash_key用python内建的哈希函数将字符串转化为数字。拿到key对应的值时,使用%模除和len(aMap)来获取放置这个key的位置
get_bucket找到key对应的位置,然后返回一个元祖(i,k,v),i索引,k是key,v是key的值
get获取元组(i,k,v)并且返回v
set 设置一个key/value键值对,存在就替换,不存在就追加
delete 删除一个key,
list属于调试,打印hashmap
三级列表
让每个bucket的插槽的值都是一个列表,给字典增加第三级列表
list是一个有序的列表,dict是一个键值对。python中collection.OrderedDict
exercis40.模块、类和对象
python是一门面向对象编程语言,也就是说python中有类的概念。
模块就像字典
- 包含一些函数和变量和python文件
- 你可以导入这个文件
- 你可以用.操作符访问这个模块的函数和变量
mystuff.py
# this goes in mystuff.py
def apple():
print("I AM APPLES!")
mystuff['apple']# get apple from dict
mystuff.apple()# get apple from the module
mystuff.tangerine# same thing, it's just a variable
类之间不会冲突,而模块之间会相互冲突,导入一个模块时整个项目也就只有这一个模块。实际上就是将代码段导入了。
类可以被实例化,得到类的对象。
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print('I AM CLASSY APPLES!')
thing = MyStuff()
thing.apple()
print(thing.tangerine)
- python 查找Mystuff()并确认它是你已经定义过的类
- python创建一个空的对象,该对象拥有你在类中用def创建的所有函数。
- python看你是否创建了__init__函数,如果有,调用该方法初始化你新创建的空对象
- 在MyStuff中,__init__方法有一个额外的变量self,这是python创建的空的对象,可以在其上设置变量
- 然后,给self.tangerine设置一首歌词,然后初始化这个对象
- python可以使用这个新创建好的对象,将其分配给我可以使用的对象thing
当你调用一个类时,python做的事情,不是把这个类给你,而是把类作为蓝本创建该类型副本。
- 类是用来创建mini模块的蓝本或定义。
- 实例化是如何创建这些小模块,并在同一时间将其导入。实例化仅仅是指通过类创建一个对象。
- 由此产生的mini模块被称为对象,你可以将其分配给一个变量,让她开始运行起来。
# dict style
mystuff['apples']
# module style
mystuff.apples()
print mystuff.tangerine
# class style
thing = MyStuff()
thing.apples()
print(thing.tangerine)
类的举例
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_bday = 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 tha family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
如果不在__init__或者其他函数时使用self。那么引用的对象就不明确,代码不清楚你用的是实例的属性韩式全局变量。如果用self.属性,就很明确你用的是实例中的属性self.cheese。
exercise41.学会说面向对象
单词解释:
class(类):告诉python去创建一个新类型。
object(对象):事物的基本类型或者事物实例化。
instance(实例):通过python创建一个类所获得的。
def:在一个类中定义一个函数。
self:在一个类包含的函数中,self是一个用来访问实例或对象的变量。
inheritance:概念,表示一个类可以继承另一个类的特征。
composition:概念,表示一个类可以包含其他类。内部类?
attribute:类所拥有的特性,通常是变量。
is-a:惯用语,表示一个东西集成自另一个东西。
has-a:表示有其他事情或有一个特征
短语解释:
class X(Y):创建一个叫X的类,并继承Y。
class X(object): def __init__(self, J): 类X中有一个__init__方法,该方法又self和J两个参数。
class X(object): def M(self,J): 类X有一个叫M的函数,该函数有self和J两个参数。
foo = X(): 给foo赋值为类X的一个实例。
foo.M(J): 从foo里调用M函数,传递的参数为self和J。
foo.K =Q:从foo里调用K属性,并将它设置为Q。
oop_test.py
更多推荐
所有评论(0)