1.first program
print() #打印
2.comments
# 添加注释,每行一个#
3.number and math
print ("Hens",25+30/6)
print (3+2<5-7)
4.variables and name
cars = 100 #变量赋值
space_in_a_car = 4.0 #变量名可以带"_"
print ("There are",cars,"cars available.") #打印变量
5.more variables and printing
my_name = 'Zed A.Shaw'
print (f"Let's talk about {my_name}.") #打印变量的第2种方式
6.string and text
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print (joke_evaluation.format(hilarious)) #打印变量的第3种方式
# 字符串连接
w = "this is the left side of ..."
e = "a string with a right side."
print (w+e)
7.more printing
print ("."*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"
# 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)
8.printing,printing
formatter = "{} {} {} {}"
print (formatter.format(1,2,3,4)) #打印变量的第3种方式
9.printing,printing,printing
months = 'Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
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.
""") #打印变量的第4种方式
10.what was that?
# 打印单引号或双引号
print ("i am 6'2\" tall.")
print ('i am 6\'2" tall.')
# 打印缩进
tabby_cat = "\tI'm tabbed in."
# 打印反斜杠
backslash_cat = "I'm \\ a \\ cat."
11.asking questions
print('how old are you?',end='')
age = input() #从外部输入信息
print(f"so,you're {age} old.")
12.prompting people
# 上一个练习的缩写
age = input("how old are you:")
print(f"you're {age} old")
13.parameters,unpacking,variables
# 引入sys库
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)
14.prompting and passing
prompts = '>>>>>>>>>>>>>>>>' #复习
likes = input(prompts)
15.reading files
txt = open(filename) #打开文件
print(f"here's your file {filename}:")
print(txt.read()) 输出文件内容
16.reading and writing files
print("opening the file...")
target = open(filename,'w') #以写入方式打开文件
print("truncating the file.goodbye!")
target.truncate() #清空文件内容
target.write(line1) #写入内容
target.write("\n")
#写入完成,关闭文件
print("and finally,we close it.")
target.close()
扩展:
17.more files
in_file = open(from_file)
indata = in_file.read() #将文件内容读入内存
18.names,variables,code,functions
def print_two(*args): #如果需要向函数传入多个变量,可以这样
arg1,arg2,arg3,arg4 = args
print(f"arg1: {arg1},arg2: {arg2},arg3: {arg3},arg4: {arg4}")
19.functions and variables
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print(f"you have {cheese_count} cheeses!")
print(f"you have {boxes_of_crackers} boxes of crackers")
# 可以向函数传入数值
cheese_and_crackers(20,30)
# 也可以这么传入数值
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
# 也可以传入公式
cheese_and_crackers(10+20,5+6)
# 也可以传入公式+数值
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
20.functions and files
def rewind(f):
f.seek(0) #指定文件指针位置
def print_a_line(line_count,f):
print(line_count,f.readline()) #read.line() :从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。
扩展
# 1.seek的用法
seek(offset [,from])方法改变当前文件的位置。
Offset:变量表示要移动的字节数。
From:变量指定开始移动字节的参考位置。
如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。
如果设为1,则使用当前的位置作为参考位置。
如果它被设为2,那么该文件的末尾将作为参考位置
21.functions can return something
def add(a,b):
print(f"ADDING {a} + {b}")
return a+b #退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None
22.what do you know so far
RETURN
23.Strings, Bytes, and Character Encodings
def main(language_file,encoding,errors):
line = language_file.readline()
if line:
print_line(line,encoding,errors)
return main(language_file,encoding,errors) #用RETURN作循环
def print_line(line,encoding,errors):
next_lang = line.strip() #移除字符串头尾指定的字符(默认为空格)
24.More Practice
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) # 赋值的数量和返回值的数量一定要一致
25.Even More Practice
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)
32.Loops and Lists
for i in range(0,6):
print(f"adding {i} to the list.")
#append is a function that lists understand
elements.append(i) # 在列表末尾添加新的对象
34.Accessing Elements of Lists
animals = ['bear','python3.6','peacock','kangaroo','whale','platypus']
print('1.',animals[1]) # 列表
35.Branches and Functions
from sys import exit
def dead(why):
print(why,"good job!")
exit(0) # sys.exit(0)---正常退出脚本,sys.exit(1)非正常退出脚本
38.Doing Things to Lists
print(' '.join(stuff)) # 将序列中的元素以指定的字符连接生成一个新的字符串
print('#'.join(stuff[3:5])) #super stellar!
***
result:
apples oranges crows telephone light sugar boy girl banana
telephone#light
39.Dictionaries, Oh Lovely Dictionaries
cities = {'ca':'san francisco',
'mi':'detroit',
'fl':'jacksonville',
}
# add some more cities
cities['ny'] = 'new york' # 向字典中增加数据
city = cities.get('mi','does not exist') # 返回指定键的值,如果值不在字典中返回默认值
print(city)
--->detroit
40.Modules, Classes, and Objects
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)
#print (counter.__secretCount) # 报错,实例不能访问私有变量
print (counter._JustCounter__secretCount) # 正确
class A:
def foo(self):
print('called A.foo()')
class B(A):
pass
class C(A):
def foo(self):
print('called C.foo()')
class D(B,C):
pass
if __name__ == '__main__':
d = D()
d.foo()
--->called C.foo()
41.Learning to Speak Object-Oriented
for word in urlopen(word_url).readlines():
words.append(str(word.strip(),encoding = "utf-8")) # .strip()移除字符串头尾指定的字符(默认为空格)
snippets = list(phrases.keys()) # 以列表返回一个字典所有的键
class_names = [w.capitalize() for w in random.sample(words,snippet.count("%%%"))] # .capitalize()首字母大写
for word in class_names:
result = result.replace("%%%",word,1) # 字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次
44.Inheritance versus Composition
class Parent(object):
def altered(self):
print("PARENT altered()")
class Child(Parent):
def altered(self):
print("CHILD, BEFORE PARENT altered()")
super(Child, self).altered() # 调用父类的函数
print("CHILD, AFTER PARENT altered()")
dad = Parent()
son = Child()
dad.altered()
son.altered()
--->
PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()
调用父类的第二种方法
class Child(object):
def __init__(self):
self.other = Other() # 调用父类
def implicit(self):
self.other.implicit()
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD, BEFORE OTHER altered()")
self.other.altered()
print("CHILD, AFTER OTHER altered()")