CH1处理字符串

输入如下代码
1234567891011121314 | phone_number = '1386-666-0006'hiding_number = phone_number.replace(phone_number[:9],'*'*9)print(hiding_number)search = '168'num_a = '1386-168-0006'num_b = '1681-222-0006'print(search + ' is at ' +str(num_a.find(search)) + ' to ' + str(num_a.find(search) + len(search)) + ' of num_a')print(search + ' is at ' +str(num_b.find(search)) + ' to ' + str(num_b.find(search) + len(search)) + ' of num_b')print('{} a word she can get what she {} for.'.format('With','came'))print('{preposition} a word she can get what she {verb} for'.format(preposition = 'With',verb = 'came'))print('{0} a word she can get what she {1} for.'.format('With','came'))city = input("write down the name of city:")url = "http://apistore.baidu.com/microservice/weather?citypinyin={}".format(city)print(url) |
显示如下:

CH2函数
创建函数

设计求三角形斜边长的函数:
123 | def (edge1, edge2): return 'The right triangle side's length is {}'.format((edge1**2 + edge2**2)**(1/2))print(computeEdge(3.0, 4.0)) |
显示结果

传递参数与参数类型
例如函数

12 | def trapezoid_area(base_up, base_down, height): return 1/2 * (base_up + base_down) * height |
位置参数传递
1 | trapezoid_area(1,2,3) |
关键词参数传递
1 | trapezoid_area(base_up=1, base_down=2, height=3) |
也可以给参数添加默认值
1 | trapezoid_area(base_up=1, base_down=2, height=3) |
设计自己的函数
打开文件并写入的函数
12345678 | def text_create(name, msg): desktop_path = '/Users/Hou/Desktop/' full_path = desktop_path + name + '.txt' file = open(full_path,'w') file.write(msg) file.close() print('Done') text_create('hello','hello world') |
过滤敏感词的函数
123 | def text_filter(word,censored_word = 'lame',changed_word = 'Awesome'): return word.replace(censored_word, changed_word) text_filter('Python is lame!') |
创建文件并输入名字,有敏感词则被过滤
1234 | def censored_text_create(name, msg): clean_msg = text_filter(msg) text_create(name,clean_msg) censored_text_create('Try','lame!lame!lame!') |
运算符

CH3循环与判断
一些简单的输入输出
middle = 5
1 < middle < 10输出
True
‘Hello’ == ‘Hello’输出
True
成员运算符与身份运算符
创建列表
1 | album = ['Black Star', 'David Bowie',25, True] |
使用append向列表尾部添加元素
1 | album.append('new song') |
打印列表中第一个和最后一个元素
1 | print(album[0], album[-1]) |
Membership Operator
关键字in
not in
1 | 'Black Star' in album |
测试字符串Black Star
是否在列表album中,如果存在就会显示True,不存在就会显示False
Identify Operator
关键字is
is not
12 | name = 'hello''hello' is name |
条件控制

循环
for循环

12 | for num in range(1,11): print(str(num) + ' + 1 =', num+1 ) |
输出
1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5
5 + 1 = 6
6 + 1 = 7
7 + 1 = 8
8 + 1 = 9
9 + 1 = 10
10 + 1 = 11
打印九九表
123 | for i in range(1,10): for j in range(1,10): print('{} X {} = {}'.format(i,j,i*j)) |
while循环

12 | while 1 < 3: print('这是while循环') |
练习题
123456789 | ##### 创建10个文本 ######def def text_creation(): path = 'G:Python_CodeTest ' for name in range(1,11): with open(path + str(name) + '.txt', 'w') as text: text.write(str(name)) text.close() print('Done')text_creation() |
输出结果

12345678910111213141516171819202122232425262728293031323334353637383940 | ####### 一个掷色子的小游戏 #######import random###摇色子的函数,返回储存三个点数结果的列表def roll_dice(numbers=3, points=None): print('<<<<< ROLL THE DICE! >>>>>') if points is None: points = [] while numbers > 0: point = random.randrange(1,7) points.append(point) numbers = numbers - 1 return points###定义Big和Smalldef roll_result(total): isBig = 11 大专栏 Python魔力手册读书笔记 <= total <= 18 isSmall = 3 <= total <= 10 if isBig: return 'Big' elif isSmall: return 'Small'####游戏开始def start_game(): print('<<<<< GAME STARTS! >>>>>') choices = ['Big', 'Small'] your_choice = input('Big or Small:') if your_choice in choices: points = roll_dice() total = sum(points) youWin = your_choice == roll_dice(total) if youWin: print('The points are', points, 'You win!') else: print('The points are', points, 'You lose!') else: print('Invalid Words') start_game()start_game()</pre> |
输出结果
<<<<< GAME STARTS! >>>>>
Big or Small:Big
<<<<< ROLL THE DICE! >>>>>
<<<<< ROLL THE DICE! >>>>>
The points are [2, 3, 1] You lose!
CH4 数据结构
列表
1 | list = [val1, val2, val3, val4] |
字典
1 | dict = {key1:val1, key2:val2} |
元组
1 | tuple = (val1, val2, val3, val4) |
集合
1 | set = {val1, val2, vla3, val4} |
列表(list)
- 列表中的每一个元素都是可变的
- 列表中的元素是有序的,也就是说每一个元素都有一个位置
- 列表可以容纳Python中的任何对象
1 | list = ['pineapple', 'pear'] |
insert()
1 | list.insert(1, 'grape') |
输出
[‘pineapple’, ‘grape’, ‘pear’]
在使用insert方法的时候,必须指定在列表中要插入新的元素的位置,插入元素的实际位置是在指定位置元素之前的位置
,如果指定插入的位置在列表中不存在,实际上也就是超出指定列表长度,那么这个元素一定会被放在列表的最后位置
remove()
1 | list.remove('grape') |
或者
123 | list = ['pineapple','grape','pear']del list[0:2]print(list) |
输出
[‘pear’]
索引

字典(Dictionary)
key - value
- 字典中数据必须是以key-value的形式出现的
- 逻辑上讲,key不能够重复,而value可以重复
- 字典中的key是不可以修改的;而value是可以修改的,可以是任何对象
1
dict = {'key1':'val1', 'key2':'val2'}
添加键值对
1 | dict['key3'] = 'val3' |
update()添加多个元素
update()方法可以用来添加多个元素
1 | dict.update({'key4':'val4', 'key5':'val5'}) |
del删除元素
1 | del dict['key2'] |
元组(Tuple)
元组可以理解成一个稳固版的列表,因为元组是不可修改的,因此在列表中的存在的方法均不可以使用在元组上,但是元组是可以被查看索引的,方式和列表中一样:
12 | letters = ('a','b','c','d','e','f','g') letter[0] |
集合(Set)
1 | a_set = {1,2,3,4} |
每一个集合中的元素是无序的、不重复的任意对象,我们可以通过集合去判断数据的从属关系,有时还可以通过集合把数据结构中重复的元素减掉

集合不能被切片也不能被索引,除了做集合运算之外,集合元素可以被添加还有删除
1234 | a_set.add(5)print('after add:' + str(a_set))a_set.discard(5)print('after discard:' + str(a_set)) |
输出
after add:{1, 2, 3, 4, 5}
after discard:{1, 2, 3, 4}
数据结构中的一些技巧
多重循环
12 | num_list = [6,2,7,4,1,3,5]print(sorted(num_list)) |
输出
[1, 2, 3, 4, 5, 6, 7]
sorted函数按照长短、大小、英文字母的顺序给每个列表中的元素进行排序
sorted
函数并不会改变列表本身,你可以把它理解成先将列表进行复制,然后再进行顺序的整理
在使用默认参数reverse后列表可以被按照逆序整理:
12 | num_list = [6,2,7,4,1,3,5]print(sorted(num_list, reverse=True)) |
输出
[7, 6, 5, 4, 3, 2, 1]
关键字zip
处理两个list

1234 | name=('jack','beginman','sony','pcky')age=(2001,2003,2005,2000)for n,a in zip(name,age): print (n, '--', a) |
输出
jack – 2001
beginman – 2003
sony – 2005
pcky – 2000
推导式

红色虚线后面的是我们熟悉的for循环的表达式,而虚线前面的可以认为是我们想要放在列表中的元素
1234 | a = [i**2 for i in range(1,10)] c = [j+1 for j in range(1,10)] k = [n for n in range(1,10) if n % 2 ==0] z = [letter.lower() for letter in 'ABCDEFGHIGKLMN' |
字典推导式的方式略有不同,主要是因为创建字典必须满足key-value的两个条件才能达成
123 | d = {i:i+1 for i in range(4)g = {i:j for i,j in zip(range(1,6),'abcde')} g = {i:j.upper() for i,j in zip(range(1,6),'abcde')} |
enumerate获取元素的索引
123 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] for num,letter in enumerate(letters): print(letter,'is',num + 1) |
输出
a is 1
b is 2
c is 3
d is 4
e is 5
f is 6
g is 7
一个词频统计的小程序
12345678910 | import stringpath = 'G:Python_CodeTestWalden.txt'with open(path, 'r') as text: # 文字首位去掉了连在一起的标点符号,并把首字母大写的单词转化成小写 words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] words_index = set(words) # 将列表用set函数转换成集合,自动去除掉了其中所有重复的元素 counts_dict = {index:words.count(index) for index in words_index}# 排序后输出for word in sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True): print('{} -- {} times'.format(word,counts_dict[word])) |