您的位置:首页 > 编程语言 > Python开发

《python编程从入门到实践》读书笔记与代码实现(一)

2020-01-14 19:28 585 查看

封面

第一部分 基础(第1-11章)

#代码放乱了,懒得按照章节形式展示(...
#-*-coding:GBK -*-
#city_functions.py

def city_country(city,country,population=''):
"""定义一个返回城市名和国家名的函数"""
'''
将population设置为一个具有默认值的可选参数
'''
if population:
msg = city.lower().title() + ',	' + country.lower().title() + ' - ' + 'population	' + str(population)
else:
msg = city.lower().title() + ',	' + country.lower().title()

return msg

#print(city_country('wuhan','china'))
#codestesting.py
# -*- coding: utf-8 -*-
'''
测试函数

单元测试和测试用例:
python标准库中的unittest提供了代码测试工具
*单元测试:核实函数的某个方面没有问题
*测试用例:
一组单元测试,一起核实函数在各种情形下的行为都符合要求
良好的测试用例考虑到了函数可能收到的各种输入,包含所有针对这种情形的测试
*全覆盖式测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式(广泛使用再考虑)
'''

'''
测试类

6个常用的断言方法
1.assertEqual(self, first, second, msg=None)
--判断两个参数相等:first == second
2.assertNotEqual(self, first, second, msg=None)
--判断两个参数不相等:first != second
3.assertIn(self, member, container, msg=None)
--判断是字符串是否包含:member in container
4.assertNotIn(self, member, container, msg=None)
--判断是字符串是否不包含:member not in container
5.assertTrue(self, expr, msg=None)
--判断是否为真:expr is True
6.assertFalse(self, expr, msg=None)
--判断是否为假:expr is False

一个需要测试的类:
测试类中方法的行为

方法setUp()
在TestCase类中创建对象一次,即可在之后的每个测试方法中对它们进行使用
可在setUp()方法中创建一系列实例并设置它们的属性,再在测试方法中直接使用这些实例

运行测试用例时,每完成一个单元测试,python均打印出一个字符。
测试通过.
测试引发错误E
测试导致断言失败F
'''

#上述训练按照课本要求分别创建对应的py文件
#dictionary.py
# coding=gbk
'''
字典可存储的信息量基本上不受限制
鉴于它“键值对”的特点,与键对应的值可以是Python中的任何对象
Python不关心键值对的添加顺序,只关心键与值之间的关联关系
'''

'''
6-1
person = {
'first_name' : 'jane',
'last_name' : 'smith',
'age' : 23,
'city' : 'helan',
}

print(person)
'''

'''
6-2和6-3的结合
person = {
'first_name' : 'jane',
'last_name' : 'smith',
'age' : 23,
'city' : 'helan',
}
print('the first_name is	' + person['first_name'] + '\n')
print('the last_name is	' + person['last_name'] + '\n')
print('the age is	' + str(person['age']) + '\n')
print('the city is	' + person['city'] + '\n')
'''

'''
遍历字典
返回值依然有可能与列表存储的顺序不同,Python只关心键值对应关系
循环时用到的方法
.items()遍历所有键值对

.keys()遍历所有键,Python中默认遍历所有键,所以该方法可省略。
同时该方法不仅仅用于遍历,它还返回一个列表,其中包含字典中的所有键。

sorted()按顺序遍历

.values()遍历所有值,返回一个值列表,而不包含任何键
该方法不考虑返回值是否重复
配合使用set()函数【集合】即可找出列表中独一无二的元素,并使用这些元素来创建一个列表
'''

'''
6-4
person = {
'first_name' : 'jane',
'last_name' : 'smith',
'age' : 23,
'city' : 'helan',
'1' : 'test1',
'2' : 'test2',
'3' : 'test3',
'4' : 'test4',
'5' : 'test5',
}
for key, value in person.items():
print('\nkey:	' + key + '	value:	' + str(value))
'''

'''
6-5
geo = {
'nile' : 'egypt',
'long river' : 'china',
'huang river' : 'china',
}
for key, value in geo.items():
print('The ' + key.title() + ' runs through ' + value.title())
print('\n')
for key in geo.keys():
print(key)
print('\n')
for value in set(geo.values()):
print(value)
'''

'''
6-6
alreadyinpoll = {
'person_a' : 'java',
'person_b' : 'c',
'person_c' : 'python',
}
persons = ['person_a','person_b','person_c','jane']
for person in persons:
if person in set(alreadyinpoll.keys()):
print(person.title() + ", thank you for taking the poll!")
else:
print(person.title() + ", please take the poll.")
'''

'''
嵌套
字典列表(列表中存储字典)
字典中存储列表:当需要一个键关联多个值时。
字典中存储字典
'''

'''
6-7、6-8
person_1 = {
'first_name' : 'jane',
'last_name' : 'smith',
'age' : 23,
'city' : 'japan',
}
person_2 = {
'first_name' : 'sam',
'last_name' : 'smith',
'age' : 33,
'city' : 'china',
}
person_3 = {
'first_name' : 'lily',
'last_name' : 'smith',
'age' : 13,
'city' : 'europe',
}
people = [person_1,person_2,person_3]
for person in people:
print(person)
'''

'''
6-9、6-10
favorite_places = {
'jane' : ['Beijing','Nanjing'],
'sam' : ['Wuhan','Shanghai'],
'sue' : ['Japan'],
}
for name, places in favorite_places.items():
if len(places) == 1:
#print(name.title() + ", your favorite place is : \n" + str(favorite_places.values()))
print('\n' + name.title() + ", your favorite place is : \n")
for place in places:
print(place)
else:
print('\n' + name.title() + ", your favorite places are : \n")
for place in places:
print(place)
#for place in favorite_places.values():
#print(place)
#需要运行出特定对象所对应的地点,上面两个全部是错误的。
'''

'''
6-11
cities = {
'Beijing' :{
'coutry' : 'china',
'population' : '1 billion',
'fact' : 'the capital of the china',
},
'Shanghai' :{
'coutry' : 'china',
'population' : '1.5 billion',
'fact' : 'the financial center of the china',
},
'Zhengzhou' :{
'coutry' : 'china',
'population' : '2 billion',
'fact' : 'a province of the china',
},
}
for key, values in cities.items():
print('\n' + key + '\n')
for value in values.values():
print(value)
'''
#employee.py
#-*-coding:GBK -*-
# -*- coding: utf-8 -*-

class Employee:
"""一个描述职员信息的类"""

def __init__(self,first_name,last_name,annual_salary):
"""初始化描述职员的属性"""
self.first_name = first_name
self.last_name = last_name
self.annual_salary = annual_salary
self.annual_raise = 5000

'''
def set_annual_raise(self, annual_raise):
"""定义一个方法修改薪水增长量"""
self.annual_raise = annual_raise
'''

def give_raise(self,annual_raise=''):
"""增加年薪的类,用户自定义的薪水量以实参形式传入"""
if annual_raise:
self.annual_salary += annual_raise#这边只写raise编译不通过,raise貌似是一个关键字无法通过编译
else:
self.annual_salary += 5000

def describe_employee_salary(self):
"""对雇员信息中的薪水进行描述"""
#msg = 'The name:	' + self.first_name + self.last_name + '\n'
return self.annual_salary
#files&exceptions.py
# -*- coding: utf-8 -*-
'''
从文件中读取数据
'''

'''
读取整个文件:

先打开
函数open()
接受一个参数,即要打开的文件的名称,Python在当前执行文件所在的目录查找指定文件
open('pi_digits.txt')返回一个表示文件pi_digits.txt的对象file_object,Python将这个对象存储在我们将在后面使用的变量中
关键词with在不再需要访问文件后将其关闭,防止close()函数在程序bug的存在下不会执行
'''

'''
with open('pi_digits.txt') as file_object:
contents = file_object.read()
#print(contents)#此处输出相比于原始文件多出一个空行,因为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来就是一个空行
print(contents.rstrip())#消除最后的空行
'''

'''
文件路径
*'pi_digits.txt',数据文件存储在当前执行文件所在目录
*相对路径,数据文件存储在当前执行文件所在目录下的一个文件夹中
*准确位置,定义file_path,可以访问文件系统中的任意位置文件
'''

'''
逐行读取
'''

'''
file_name = 'pi_digits.txt'

with open(file_name) as file_object:
for line in file_object:
#print(line)#每行末尾都有一个看不见的换行符,而print语句也会加上一个换行符
print(line.rstrip())
'''

'''
创建一个包含文件各行内容的列表
当你想在with代码块外访问文件的内容时,可在with代码块内将文件的各行存储在一个列表中
'''

'''
file_name = 'pi_digits.txt'

with open(file_name) as file_object:
lines = file_object.readlines()#函数readlines()从文件中读出一行并将它存储到变量lines中

for line in lines:
print(line.rstrip())
'''

'''
使用文件的内容

读取文本文件时,Python将所有文本都解析为字符串
当读取数字且当作数值使用,需要使用函数int()转换为整数,函数float()转换为浮点数
'''

'''
file_name = 'pi_digits.txt'

with open(file_name) as file_object:
lines = file_object.readlines()#函数readlines()从文件中读出一行并将它存储到变量lines中

pi_string = ''

for line in lines:
pi_string += line.strip()

print(pi_string)
print(len(pi_string))
'''

'''
包含一百万位的大型文件
Python对处理的数据量没有限制
'''

'''
10-1,一个文件对象只能使用一次
file_name = 'learning_python.txt'

with open(file_name) as file_object:
print('the second\n')
for line in file_object:
print(line.strip())
#contents = file_object.read()
#print('the first\n')
#print(contents)
#lines = file_object.readlines()#函数readlines()从文件中读出一行并将它存储到列表变量lines中

#print('the third\n')
#third_string = ''
#for line in lines:
#	third_string += line.strip() + '\n'
#print(third_string)
'''

'''
10-2
file_name = 'learning_python.txt'

with open(file_name) as file_object:
lines = file_object.readlines()#函数readlines()从文件中读出一行并将它存储到列表变量lines中

third_string = ''
for line in lines:
third_string += line.replace('python','c').strip() + '\n'
print(third_string)
'''

'''
写入文件
write()

写入空文件,open()函数的不同参数
w 写入,指定文件已存在时,使用该参数将会把原始文件内容全部清空再返回
r 读取
a 附加到文件末尾,不会清空文件内原有的内容,如果指定的内容不存在,会新建
r+ 读取和写入
忽略以上参数时,Python将默认以只读模式打开
写入的文件不存在时,open()函数将自动创建
python只能将字符串写入文本文件,如果要存储如数值一类的其他类型数据,要先将它用str()函数进行转换

写入多行
write()函数不会向输入内容的末尾添加换行符,需要自己添加

附加到文件
a
'''

'''
10-3
name = input('Please input your name:	')
#print(name)
file_name = 'guest.txt'
#with open(file_name , w) as file_object:语法错误
with open(file_name,'w') as file_object:
file_object.write(name)
'''

'''
10-4
file_name = 'guest_book.txt'
while True:
name = '\nPlease input your name:\n'
name +='You can end the program by inputting q\n'
message = input(name)
if message == 'q':
break
else:
#with open(file_name,'w') as file_object:使用'w'只会保留循环填写的最后一次结果,只有使用'a'才能不断在文件后面进行添加
with open(file_name,'a') as file_object:
file_object.write(message + '\n')
'''

'''
异常
一个特殊对象,用来管理程序执行期间发生的错误
每当发生一个让python不知所措的错误时,均会创建一个异常对象
编写了针对该异常的代码,程序将继续进行;否则程序将在异常处停止并显示一个traceback提示错误代码。
ZeroDivisionError、FileNotFoundError

处理异常:
try-except代码块
try 尝试运行一些可能出现异常的代码
except 捕获错误,如果出现问题之后应该怎么办
运行后,程序将继续执行

else 依赖于try代码块成功执行的代码

通过预测可能发生异常的代码,可编写健壮的程序

分析文本
方法split(),根据一个字符串以空格为分隔符创建一个单词列表

使用多个文件
包装为函数并进行调用

失败时一声不吭
pass语句
可以在异常发生时一声不吭,继续执行其他内容
充当占位符,告诉用户在哪里什么都没有做

python的错误处理结构能够细致控制与用户分享错误信息的程度
'''

'''
10-7
print('Please give me two numbers, and I will add them.')
print('Enter q to quit.')

while True:
first_number = input('the 1st:	')
if first_number == 'q':
break
second_number = input('the second:	')
if second_number == 'q':
break
try:
int(first_number)
except TypeError:
print('The 1st is not an integer.')
else:
try:
int(second_number)
except TypeError:
print('The 2nd is not an integer.')
else:
answer = int(first_number) + int(second_number)
print(answer)
'''

'''
10-10
file_name = 'Miss Billy.txt'

try:
with open(file_name,encoding='UTF-8') as file_object:
contents = file_object.read()#read()函数返回一个字符串
except FileNotFoundError:
message = 'Sorry, the book ' + file_name + ' dose not exist!'
print(message)
else:
#words = contents.split()#生成整篇文章单词的列表形式,但是列表本身没有lower()函数
print(contents.lower().count('the'))
'''

'''
存储数据
模块JSON
'''

'''
import json
numbers = [1,2,3,4]
file_name = 'numbers.json'
with open(file_name,'w') as file_object:
json.dump(numbers,file_object)#两个参数分别表示等待存储的数据和可用于存储数据的文件对象
with open(file_name) as file_object:
numbers = json.load(file_object)#将列表读入内存中
print(numbers)
'''

'''
保存和读取用户生成的数据:
结合JSON模块和try-except-else结构
'''

import json

file_name = 'f_number.json'
try:
"""如果数字曾经存储过,就将它直接读入内存"""
with open(file_name) as file_object:
number = json.load(file_object)#将列表读入内存中
except:
"""否则提示用户"""
number = input('Please input your favorite number:	')
with open(file_name,'w') as file_object:
json.dump(number,file_object)#两个参数分别表示等待存储的数据和可用于存储数据的文件对象
print('We will remember the number when you come back.')
else:
print('Welcome back, the number is ' + number)

'''
重构
'''
#functions.py
# -*- coding:utf-8 -*-

'''
定义函数、调用函数
向函数传递信息
实参和形参各是哪一个
'''

'''
8-1
def display_message():
print('In this part, you can learn something about the function.')

display_message()
'''

'''
8-2
def favorite_book(title):
print('One of my favorite book is ' + title.title())

favorite_book('alice in wonderland')
'''

'''
传递实参:
位置实参——实参顺序与形参顺序相同,可以根据需求调用函数多次
关键字实参——每个实参由关键字和变量组成,关键词实参的顺序无关紧要,但要准确指定形参名

不使用关键字实参的默认均为位置实参

函数定义时有默认值的形参可以不用传入实参,若再显性传入则以显性传入的为准
使用默认值时必须先列出没有默认值的形参,再列出有默认值的形参

列表
字典
'''

'''
8-3
def make_shirt(size,slogan):
print('The size of the shirt is ' + size + ', and the slogan on it is:	' + slogan)

make_shirt('S','I have a dream one day!')
make_shirt(slogan = 'I have a dream one day!', size = 'S')
'''

'''
8-4、8-5
def make_shirt(size, slogan = 'I love Python!'):
print('The size of the shirt is ' + size + ', and the slogan on it is:	' + slogan)

make_shirt('L')
make_shirt('M')
make_shirt('S','test')
'''

'''
[函数返回值]
*返回简单值,适用于处理大量数据
*让实参变为可选的:可选的参数使用空字符串作为默认值,并使用if做条件判断
*返回字典
*结合使用函数和while循环
'''

'''
8-6
def city_country(city_name, country_name):
return city_name + ' , ' + country_name

print(city_country('WuHan','China'))
'''

'''
8-7
def make_album(singer_name, album_name):
album = {
'singer_name' : singer_name,
'album_name' : album_name,
}
return album

album_1 = make_album('a', 'aa')
album_2 = make_album('b', 'bb')
album_3 = make_album('c', 'cc')
print(album_1)
print('\n')
print(album_2)
print('\n')
print(album_3)
'''

'''
8-8
def make_album(singer_name, album_name):
album = {
'singer_name' : singer_name,
'album_name' : album_name,
}
return album

while True:
print('\nplease tell me your album.\n')
print('you can use q to end the program at any time.\n')

s_n = input("the singer's name:	")
if s_n == 'q':
break

a_n = input("the album's name:	")
if a_n == 'q':
break

album = make_album(s_n, a_n)
print(album)
'''

'''
传递列表

在函数中修改列表:
每一个函数都应只负责一项具体的工作
可以在一个函数中调用另一个函数

禁止函数修改列表:
切片表示法
传递列表时,如无必要,尽量传递原始列表,以减小资源和时间消耗
'''

'''
8-9
def show_magicians(magicians):
for magician in magicians:
print(magician)
magicians = ['a','b','c']
show_magicians(magicians)
'''

'''
8-10
def make_great(unchanged_magicians, magicians):
if unchanged_magicians:
for unchanged_magician in unchanged_magicians:
unchanged_magician = 'the Great ' + unchanged_magician
magicians.append(unchanged_magician)

def show_magicians(magicians):
for magician in magicians:
print(magician)

unchanged_magicians = ['a','b','c']
magicians = []
make_great(unchanged_magicians, magicians)
show_magicians(magicians)
'''

'''
8-11
def make_great(unchanged_magicians, magicians):
if unchanged_magicians:
for unchanged_magician in unchanged_magicians:
unchanged_magician = 'the Great ' + unchanged_magician
magicians.append(unchanged_magician)

def show_magicians(magicians):
for magician in magicians:
print(magician)

unchanged_magicians = ['a','b','c']
unchanged_magicians_copy = unchanged_magicians[:]
magicians = []
make_great(unchanged_magicians_copy, magicians)#使用副本,不改变原始列表数据
show_magicians(magicians)
show_magicians(unchanged_magicians)
show_magicians(unchanged_magicians_copy)
'''

'''
传递任意数量的实参:
形参前加*生成一个空元组可以实现对任意数量实参的接收。

结合使用位置实参和任意数量实参:
接纳任意数量的实参的形参放在最后,Python先匹配位置实参和关键词实参,剩下的内容全部放在最后的任意数量实参中

使用任意数量的关键词实参:
接受任意数量的实参,但预先不知道传递给函数的是什么样的信息,可以使用键值对的方式直接传入一个任意数量的关键词实参
'''

'''
8-12
def get_ingredients(*ingredients):
print('the ingredients in the sandwich are:')
for ingredient in ingredients:
print(ingredient)

get_ingredients('a')
get_ingredients('a','b')
get_ingredients('a','b','c')
'''

"""
8-13
def user_profile(first, last, **user_info):
'''创建一个字典,其中包含我们知道的有关用户的一切'''
profile = {}
profile['first'] = first
profile['last'] = last
for key, value in user_info.items():
profile[key] = value
return profile

my_profile = user_profile('Xi', 'Wu', location = 'WHU', field = 'NLP')
print(my_profile)
"""

"""
8-14
def make_car(producer, model, **car_info):
'''创建一个字典,其中包含我们知道的有关汽车的一切'''
car = {}
car['producer'] = producer
car['model'] = model
for key, value in car_info.items():
car[key] = value
return car

car = make_car('subaru', 'outback', color = 'blue', tow_package = True)
print(car)
"""

'''
函数优点:
代码块与主程序分离,通过给函数指定描述性名称,提高主程序易读性。

将函数存储在被称为“模块”的独立文件(以.py结尾)中,再用import语句进行导入。
*导入整个模块
import module_name
函数调用
module_name.function_name()
*导入特定的函数
from module_name import function_name_1,function_name_2,...
函数调用
function_name()
*使用as给函数指定别名
from module_name import function_name as fn
函数调用
fn()
*使用as给模块指定别名
import module_name as mn
代码简洁,专注于描述性的函数名
*导入模块中的全部函数
from module_name import *
使用并非自己编写的大型模块时,尽量不要使用这种导入方法

推荐做法:
只导入你需要的函数
导入整个模块然后再使用句点表示法
'''

'''
函数编写指南:
*给函数、模块指定描述性名称,且只在其中指定小写字母和下划线
*每个函数都应包含简要阐述其功能的注释,紧跟函数定义之后,采用文档字符串格式
*给形参指定默认值时,等号两边不要加空格
*函数调用中的关键字实参,等号两边不要加空格
*代码行长度不超过79字符
*形参长,在函数定义中输入左括号后按回车键,并在下一行按两次TAB键,将形参列表与函数体分开
*程序模块中包含多个函数,用两个空行将相邻的函数分开
'''

#8-15尝试使用模块导入和函数调用
#if_statements.py
# coding=gbk

'''
#在python中检查是否相等包含大小写的检查
test_1 = 'XSWL'
test_2 = 'xswl'
print(test_1 == test_2)
#输出为False
'''

'''
当认为大小写重要时,if比较的特性可取,
反之可以使用lower函数进行转化,不会影响原值
网站验证用户名是否重合时常用这种方式
test_1 = 'XSWL'
test_2 = 'xswl'
print(test_1.lower() == test_2)
print(test_1)
'''

'''
#5-2
print(1 == 1)
print(1 != 1)
print(1 > 1)
print(1 < 1)
print(1 >= 1)
print(1 <= 1)
if(1==2)or(4<5):
print('You are clever')
if('XSWL'=='xsml')and(10>100):
print('wtf')
'''

'''
#列表中是否存在某一个值
#test = list[range(1,11)]语法错误
test = list(range(1,11))
print(test)
if 1 in test:
print('hello world')
if 2 not in test:
print('you are wrong')
else:
print('oooooo')
'''

'''
if-elif-else功能强大,适用于只有一个条件满足的情况.
如果要运行多个代码块,就使用一系列独立的if语句
'''

'''
alien_color = 'red'
if alien_color == 'green':
print('you got 5 points')
'''

'''
alien_color = 'green'
if alien_color == 'green':
print('you got 5 points')
'''

'''
alien_color = 'green'
if alien_color == 'green':
print('you got 5 points')
elif alien_color == 'yellow':
print('you got 10 points')
else:
print('you got 15 points')
'''

'''
alien_color = 'yellow'
if alien_color == 'green':
print('you got 5 points')
elif alien_color == 'yellow':
print('you got 10 points')
else:
print('you got 15 points')
'''

'''
alien_color = 'red'
if alien_color == 'green':
print('you got 5 points')
elif alien_color == 'yellow':
print('you got 10 points')
else:
print('you got 15 points')
'''

'''
age = 23
if age < 2:
print('He is a baby')
elif 2 <= age <4:
print('He is a toddler')
elif 4 <= age < 13:
print('He is a child')
elif 13 <= age < 20:
print('He is a teenager')
elif 20 <= age < 65:
print('He is an adult')
elif 65 <= age:
print('He is the aged')
'''

'''
fav_fruits = ['bananas','apples','oranges']
if 'bananas' in fav_fruits:
print('you really like bananas')
if 'apples' in fav_fruits:
print('you really like apples')
if 'oranges' in fav_fruits:
print('you really like oranges')
if 'bananas' and 'apples' in fav_fruits:
print('you really like bananas')
if 'bananas' and 'oranges' in fav_fruits:
print('you really like bananas')
'''

'''
5-8
#使用if语句处理列表
users = ['admin','sam','jane','bob','lily']
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello Eric, thank you for logging in again.')
'''

'''
5-9
users = []
if users:
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello Eric, thank you for logging in again.')
else:
print('we need to find some users')
'''

'''
5-10
current_users = ['admin','sam','jane','bob','lily']
new_users = ['a','b','c','d','ADMIN']
for new_user in new_users:
if new_user.lower() in current_users:
print('you need to input other names.')
else:
print('the name is valid.')
'''

'''
5-11
numbers = list(range(1,10))
for number in numbers:
if number == 1:
print(str(number) + "		1st")
elif number == 2:
print(str(number) + "		2nd")
elif number == 3:
print(str(number) + "		3rd")
else:
print(str(number) + "		"+str(number)+"th")
'''

#代码格式规范,在运算符两侧均添加空格
#list_3.py
'''
#对列表的简单打印,将打印出包括结构的整个列表内容
list = ['a','b','c']
print(list)

#打印列表中具体某一个元素,索引从0开始,而不是从1开始
print(list[0])
print(list[0].title())

#常用的访问最后一个列表元素的索引方法
print(list[-1])
'''

'''
names = ['Sam','Sun','Jane','Jamie']
print(names[0] + "  hello!")
print(names[1] + "  hello!")
print(names[2] + "  hello!")
print(names[3] + "  hello!")
'''

'''
names = ['Sam','Sun','Jane','Jamie']
#修改列表元素
names[0] = 'Dan'
#print(names)

#增添列表元素
#在末尾,可以事先创建一个空列表,然后再添加元素内容,以实现对用户行为的控制
names.append('Sam')
#print(names)
#在任意位置插入元素,插入序号从0开始
names.insert(0,'Ben')
#print(names)

#删除列表元素
#永久删除,需要知道要删除的元素的索引值
del names[0]
#print(names)
#删除列表末尾的元素并在之后继续使用
pop_names = names.pop()
#print(pop_names)
#print(names)
#删除列表任意位置的元素并在之后继续使用
first_pop_names = names.pop(0)
#print(first_pop_names)
#print(names)
#根据值删除元素,也可以继续使用该值
remove_example = 'Sun'
names.remove(remove_example)#remove函数只会删除在列表出现的第一个值,可能存在的其他相同的值需要使用循环解决
print(names)
print('\n' + remove_example.upper() + '   hello !')
'''

#列表组织
#永久性排序
#names = ['Sam','Sun','Jane','Jamie']
#names.sort()#正序
#print(names)
#names.sort(reverse = True)#倒序
#print(names)

#暂时性排序与显示
#print(sorted(names))#正序
#print(names)
#print(sorted(names,reverse = True))#倒序

#反转列表元素的排列顺序
#names.reverse()
#print(names)
#原来的错误写法print(names.reverse()),对应的方法没有返回值

#确定列表的长度
#print(len(names))
#对比上面的错误写法,可以知道相对而言len函数是有返回值的
#python中计算列表元素数时,从1开始

places = ['dali','lijiang','bolan','eluosi','laowo']
#print(places)列表原始结构
'''
print(sorted(places))#按照字母原始顺序排列,不会改变列表在内存的存储方式
print(places)
print(sorted(places,reverse=True))
print(places)
'''
'''
places.reverse()
print(places)
places.reverse()
print(places)
'''
'''
places.sort()
print(places)
places.sort(reverse = True)
print(places)
'''
#list_manipulate_4.py
#import win_unicode_console
#win_unicode_console.enable()
'''
#遍历整个列表
places = ['dali','lijiang','bolan','eluosi','laowo']
for place in places:
print(place)
'''

'''
#for循环中,添加多少行代码均可,注意缩进
places = ['dali','lijiang','bolan','eluosi','laowo']
for place in places:
print(place.title() + "  is a great site !")
print(place.title() + "  test")#两行代码缩进一致,循环同级
'''

'''
places = ['dali','lijiang','bolan','eluosi','laowo']
for place in places:
print(place.title() + "  is a great site !")
print(place.title() + "  test")#多缩进,无法运行
'''

#创建数值列表
'''
#生成一系列的数字
for value in range(1,5):
print(value)
#输出结果是纵列1,2,3,4,取值范围是左闭右开
'''
#创建数字列表
#numbers = list(range(1,6))
#print(numbers)

#指定步长
#even_numbers = list(range(1,11,2))#逻辑错误,是一个左闭右开的结构,所以将打印出所有的奇数值
#print(even_numbers)
#even_numbers = list(range(2,11,2))
#print(even_numbers)

#创建任意需要的数字集
#创建一个列表,其中包含前十个整数的平方
#squares = []
#numbers = list(range(1,11))
#for number in numbers:
#    square = number**2
#    squares.append(square)
#print(squares)

'''
#对数字列表执行简单的统计计算
digits = [0,25,41,10]
print(min(digits))
print(max(digits))
print(sum(digits))
'''

'''
#列表解析,简化创建列表的代码
squares = [value**2 for value in range(1,11)]
print(squares)
'''

'''
4-3
numbers = list(range(1,21))
for number in numbers:
print(number)
'''

'''
4-4
import win_unicode_console
win_unicode_console.enable()
numbers = list(range(1,1000001))
for number in numbers:
print(number)
'''

'''
4-5
numbers = list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
'''

'''
4-6
#odd_numbers = list(range(1,21),2))语法错误
odd_numbers = list(range(1,21,2))
for odd_number in odd_numbers:
print(odd_number)
'''

'''
4-7
three_numbers = list(range(3,31,3))
for three_number in three_numbers:
print(three_number)
'''

'''
4-8
thrs = []
numbers = list(range(1,11))
for number in numbers:
value = number**3
thrs.append(value)
for thr in thrs:
print(thr)
'''

'''
4-9
thrs = [value**3 for value in range(1,11)]
print(thrs)
'''

'''
处理列表的部分元素,切片,左闭右开
处理批量数据
'''

'''
4-10
thrs = [value**3 for value in range(1,11)]
print(thrs)
print("the first 3 items in the list are:\n")
for thr in thrs[:3]:
print(thr)
print("the middle 3 items in the list are:\n")
for thr in thrs[3:6]:
print(thr)
print("the last 3 items in the list are:\n")
for thr in thrs[-3:]:
print(thr)
'''

'''
places = ['dali','lijiang','bolan','eluosi','laowo']
#friend_places = places 这种赋值方式对同一个列表生成两个栈中的变量名称。
#下面是一个存储不同列表副本的方式
friend_places = places[:]
#print(friend_places)
places.append('home')
print("the places are:\n")
for place in places:
print(place)
friend_places.append('family')
print("the friend_places are:\n")
for friend_place in friend_places:
print(friend_place)
'''
#name_2.py
"""
字符串相关,调试成功的将被注释掉
"""

'''
name = "david smith"
print(name.title())#以首字母大写的方式显示每个字符
'''

'''
name = "abdinYHN"
print(name.upper())#将全部字母转换为大写形式
print(name.lower())#将全部字母转换为小写形式,在真实的场景中更为常用
'''

'''
first_name = "david"
last_name = "smith"
full_name = first_name + " " + last_name # 字符串拼接
print("Hello," + full_name.title() + "!")# 在输出时,可以将输出内容赋值给一个变量
'''

'''
#用制表符和换行符添加空白
print("language:\n\tpython\n\tC\n\tjava")
'''

'''
#删除空白的函数,常用于存储用户输入前对数据进行清洗
example = "   this is an example   "
#删除左侧空白
e = example.lstrip()
print(e)
#删除右侧空白
e = example.rstrip()
print(e)
#删除两边空白
e = example.strip()
print(e)
print(example)
#在上述的代码中,只有将函数返回值进行赋值才能真正永久改变变量的值
'''
#number_2.py
'''
字符串转换函数防止字符串和数字在一起识别失败
'''

'''
age = "23"

print("Happy  " + str(age) + "  birthday !")
'''

'''
import this,在终端输入这样的代码可以看到python之禅全部内容
'''

'''
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
#objoriented_class.py
# -*- coding: utf-8 -*-
'''
面向对象编程

实例化:根据类来创建对象
'''

'''
创建和使用类
类中的函数称为方法
*Python默认方法与普通方法——
默认方法:
__init__(self,)
self形参必不可少并且位于其他参数前面
Python调用默认方法时自动传入实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法
以self为前缀的变量可供类中的所有方法使用,可通过类的任何实例来访问这些变量
*属性:通过实例访问的变量

根据类创建实例
默认方法:
__init__(self,)没有显式写出return语句,但Python自动返回一个表示这条小狗的实例
首字母大写的单词被看作类,首字母小写的是实例
*访问属性 instance_name.attribute_name
*调用方法 instance_name.function_name
*创建多个实例
'''

'''
9-1
class Restaurant():
"""一个描述餐厅的类"""

def __init__(self,restaurant_name,cuisine_type):
"""初始化描述餐厅的属性"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type

def describe_restaurant(self):
"""描述餐厅属性的类"""
print('the name of the restaurant:	' + self.restaurant_name)
print('the type of the cuisine:	' + self.cuisine_type)

def open_restaurant(self):
"""表示餐厅开始营业"""
print('Open now!')

the_restaurant = Restaurant('a', 'b')
the_restaurant.describe_restaurant()
the_restaurant.open_restaurant()
'''

'''
使用类和实例:

*给属性指定默认值:类中的每个属性都必须有初始值

*修改属性的值:
直接修改:通过实例访问并修改
通过方法修改:将值传给一个更新属性的方法
通过方法对属性的值进行递增:
'''

'''
class Restaurant():
"""一个描述餐厅的类"""

def __init__(self, restaurant_name, cuisine_type):
"""初始化描述餐厅的属性"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0#对9-1的程序设置某个参数的默认值

def describe_restaurant(self):
"""描述餐厅属性的类"""
message_1 = 'the name of the restaurant:	' + self.restaurant_name + '\n'
message_2 = 'the type of the cuisine:	' + self.cuisine_type
message = message_1 + message_2
return message

def open_restaurant(self):
"""表示餐厅开始营业"""
print('Open now!')

def read_number_served(self):
"""打印一条显示在餐厅就餐人数的信息"""
print('the number of people having lunch in the restaurant:	' + str(self.number_served))

def set_number_served(self, number):
"""定义一个方法修改number_served的值"""
self.number_served = number

def increment_number_served(self, count):
"""
定义一个方法递增地修改number_served的值
需要注意根据显示语义递增值是否能为负值
同时控制细节,保证值不会被任何人随意修改
"""
if count >= 0:
self.number_served += count
else:
print("The input cannot be negative, and the number_served won't be changed.")

restaurant = Restaurant('a', 'b')
print(restaurant.describe_restaurant())
restaurant.open_restaurant()
#restaurant.read_number_served() 将直接输出原始默认值
'''

'''
#直接修改number_served的值
restaurant.number_served = 10
restaurant.read_number_served()
'''

'''
#定义一个方法修改number_served的值
restaurant.set_number_served(20)
restaurant.read_number_served()
'''

'''
#定义一个方法递增地修改number_served的值
restaurant.set_number_served(20)
#restaurant.increment_number_served(10)递增量是一个正数,通过检查
#restaurant.increment_number_served(0)递增量是0,通过检查
restaurant.increment_number_served(-10)
restaurant.read_number_served()
'''

'''
继承
当你编写的类是另一个现成类的特殊版本时可以考虑使用继承
具体实现时只需要为特殊版本特有的属性和行为编写代码

创建子类时,父类必须包含在当前文件中,且位于子类前面
定义子类时,括号内指定父类的名称
方法 __init__()接受创建car实例所需要的信息
特殊函数super(),关联父类和子类

给子类创建特有的属性和方法

重写父类的方法:
子类中定义一个方法,该方法与父类中的某个方法同名

将实例用作属性:
属性、方法清单越来越长时,可以将类的一部分作为一个独立的类提取出来,将大型类拆分成多个协同工作的小类

模拟实物:
对现实世界的建模没有高低之分,有的效率高有的效率相对较低,需要多次尝试
'''

'''
9-6
class Restaurant():
"""一个描述餐厅的类"""

def __init__(self, restaurant_name, cuisine_type):
"""初始化描述餐厅的属性"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0#招待顾客数量的默认值

def describe_restaurant(self):
"""描述餐厅属性的类"""
message_1 = 'the name of the restaurant:	' + self.restaurant_name + '\n'
message_2 = 'the type of the cuisine:	' + self.cuisine_type
message = message_1 + message_2
return message

def open_restaurant(self):
"""表示餐厅开始营业"""
print('Open now!')

def read_number_served(self):
"""打印一条显示在餐厅就餐人数的信息"""
print('the number of people having lunch in the restaurant:	' + str(self.number_served))

def set_number_served(self, number):
"""定义一个方法修改number_served的值"""
self.number_served = number

def increment_number_served(self, count):
"""
定义一个方法递增地修改number_served的值
需要注意控制语义递增值是否能为负值
同时控制细节,保证值不会被任何人随意修改
"""
if count >= 0:
self.number_served += count
else:
print("The input cannot be negative, and the number_served won't be changed.")

class Flavors():
"""一个描述冰淇淋口味的类"""

def __init__(self):
"""使用一个列表形参以生成一个冰淇凌口味列表"""
self.ice_cream_flavors = ['1','2','3']#给属性指定默认值,现实生活中的冰淇淋店的口味也是确定的

def show_ice_cream_flavors(self):
"""显示这些冰淇淋的方法"""
print('The flavors are as follows:	\n')
for ice_cream_flavor in self.ice_cream_flavors:
print(ice_cream_flavor)

class IceCreamStand(Restaurant):
"""定义一个冰淇凌店,它是一种特殊的餐厅,继承了上述餐厅类"""

def __init__(self, restaurant_name, cuisine_type):
"""初始化父类的属性"""
super().__init__(restaurant_name, cuisine_type)
#定义子类所特有的口味属性,用于将冰淇淋的各种口味存储在列表中并展示,此处使用将实例作为属性的方式
self.flavors = Flavors()

#创建一个冰淇凌实例并且用它来调用相关的方法
my_icecream_stand = IceCreamStand('a','b')
my_icecream_stand.flavors.show_ice_cream_flavors()
'''

'''
导入类:
将类存储在模块中,然后再导入模块。

导入单个类:
将大部分逻辑放在一个单独的文件中,确定类工作正常就可以专注于主程序的高级逻辑

在一个模块中存储多个类

从一个模块中导入多个类
用逗号分隔各个类

导入整个模块
使用句点法引用各个需要的类
(不推荐使用from module.name import *)

在一个模块中导入另一个模块

自定义工作流程
'''

'''
Python标准库
'''

'''
6-4
person = {
'first_name' : 'jane',
'last_name' : 'smith',
'age' : 23,
'city' : 'helan',
'1' : 'test1',
'2' : 'test2',
'3' : 'test3',
'4' : 'test4',
'5' : 'test5',
}
for key, value in person.items():
print('\nkey:	' + key + '	value:	' + str(value))
'''

'''
9-13
from collections import OrderedDict

person = OrderedDict()

person['first_name'] = 'jane'
person['last_name'] = 'smith'
person['age'] = 23
person['city'] = 'helan'

for key, value in person.items():
print(key + '	' + str(value))
'''

'''
9-14
from random import randint

class Die():
"""一个描述骰子的类"""

def __init__(self,sides = 6):
"""初始化描述骰子的属性"""
self.sides = sides #为属性设置默认值是6

def roll_die(self):
"""打印位于1和骰子面数之间的随机数"""
x = randint(1,self.sides)
print(x)

my_die_6 = Die()
my_die_6.roll_die()

my_die_10 = Die(10)
my_die_10.roll_die()

my_die_20 = Die(20)
my_die_20.roll_die()
'''

'''
类编码风格
类名:驼峰命名法,不使用下划线
实例名、模块名:小写、单词之间使用下划线

每个类在编码之后紧跟一个文档字符串:该文档字符串简要描述类的功能,遵循编写函数的文档字符串时采用的格式约定

类中一个空行来分隔方法,模块中两个空行分隔类

导入模块时,先导入标准库模块的import语句;加一个空行再导入自己编写模块的import语句
'''
#test_cities.py
#-*-coding:GBK -*-

import unittest
from city_functions import city_country

class CitiesTestCase(unittest.TestCase):
"""测试city_functions.py"""

def test_city_country(self):
"""能够正确地处理像WuHan,China这样的情况么"""
city_country_1 = city_country('WuHan','China')
self.assertEqual(city_country_1, 'Wuhan,	China')

def test_city_country_population(self):
"""
能够正确地处理像WuHan,China,100000这样的情况么
这样编写的结果就是,上述两种情况不能同时被处理,因此将population设置为可选的参数
"""
city_country_population_2 = city_country('WuHan','China',100000)
self.assertEqual(city_country_population_2, 'Wuhan,	China - population	100000')

unittest.main()
#test_employee.py
# -*- coding: utf-8 -*-

import unittest
from employee import Employee

class TestEmployee(unittest.TestCase):
"""编写一个类来测试类Employee"""

def setUp(self):
"""创建一个雇员的基本信息,并且使薪水增长可以取默认值和后来改变的值"""
self.my_employee = Employee('Xi','Wu',0)

def test_give_default_raise(self):
"""测试默认的薪资涨幅是否能够通过"""
self.my_employee.give_raise()
employee_having = self.my_employee.describe_employee_salary()
self.assertEqual(str(employee_having),str(5000))

def test_give_custom_raise(self):
"""测试用户个人设置的薪资涨幅是否能按照预设通过"""
self.my_employee.give_raise(100)
employee_having_2 = self.my_employee.describe_employee_salary()
self.assertEqual(str(employee_having_2),str(100))

unittest.main()
#tuple.py
# coding=gbk
#列表用于存储经常变化的数据,而元组则是程序整个生名周期内均不会改变的值

'''
#元组定义
dimentions = (200,50)
print(dimentions[0])
print(dimentions[1])
'''

'''
#元组值修改方式
dimentions = (200,50)
#dimentions[0] = 1000 #元组的每一个元素不能修改
#但是可以给存储元素的变量赋值
dimentions = (1000,100)
for dimention in dimentions:
print(dimention)
'''

'''
#元组遍历
dimentions = (200,50)
for dimention in dimentions:
print(dimention)
'''

'''
代码格式设置:
以制表符形式缩进
每行不超过80字符
使用空行组织程序文件
访问 https://python.org/dev/peps/pep-0008/ ,阅读 PEP 8 格式设置指南
'''
#while&input.py
# coding=gbk

'''
接收用户输入:
input()函数
使程序逻辑更为清晰
将数值作为输入用于计算和比较前,务必将其转化为数值表示

求余数:
求模运算符%
'''

'''
7-1
input('Which kind of cars do you want:	')
print('Let me see if I can buy you a Subaru.')
'''

'''
7-2
count = input('How many people eat out taday:	')
count = int(count)
if count > 8:
print('There is no table available.')
else:
print('You can take a seat.')
'''

#python中的数据类型转换:
#*int(x,base=10)x字符串或数字,base进制数,默认十进制 浮点转为整数
#*float 整数转换为浮点型
#*complex(1,2) 转换为复数
#*str(10)将对象转换为字符串
#*repe()将对象转换为表达式字符串
#*repr(dict)将对象转换为表达式字符串
#*eval(str)用来计算在字符串中有效的python表达式,返回一个对象
#*tuple(listi)将列表转化为元组
#*list()将元组转换为列表
#*set转换集合
'''
7-3
number = input('Enter a number, and I will tell you if it is multiple of 10 or not:	')
number = float(number)
if number % 10 == 0:
print('It is multiple of 10')
else:
print('It is not multiple of 10')
'''

#标志:在要求很多条件都需要满足的程序中,定义的一个变量,用于判断整个程序是否处于活动状态
#流程控制语句break,立即退出while等各种python中的循环,不再运行循环中剩余的代码,也不管条件测试的结果如何
#在循环中使用continue,返回到循环开头,并根据条件测试结果决定是否继续执行循环
#避免无限循环,需停止可按ctrl+c或者关闭显示程序输出的终端窗口
'''
7-4
prompt = '\nPlease enter your pizza ingredients.'
prompt += '\nYou can end the program by input the word quit.'
message = ''
while message != 'quit':
message = input(prompt)
if message != 'quit':使用条件测试来结束循环
print('We will add this kind of ingredient:	' + message)
'''

'''
7-5
prompt = '\nTell me your age, and I will show you the ticket price.'
prompt += '\nYou can end the program by input the word quit.'
message = ''
while message != 'quit':
message = input(prompt)
if message != 'quit':
if int(message) < 3:
print('Free of charge.')
elif 3 <= int(message) <= 12:
print('$10')
else:
print('$15')
'''

'''
使用标志控制循环
prompt = '\nPlease enter your pizza ingredients.'
prompt += '\nYou can end the program by input the word quit.'
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print('We will add this kind of ingredient:	' + message)
'''

'''
使用break控制循环
prompt = '\nPlease enter your pizza ingredients.'
prompt += '\nYou can end the program by input the word quit.'
while True:
message = input(prompt)
if message == 'quit':
break
else:
print('We will add this kind of ingredient:	' + message)
'''

'''
使用while循环来处理列表和字典
for循环只应遍历不应修改,否则导致python难以追踪其中的元素
但是在while循环中既可遍历也可修改

在列表之间移动元素
.pop()[删除列表末尾的元素并在之后继续使用]
.append()

删除包含特定值的所有列表元素
.remove()

使用用户输入填充字典
'''

'''
7-8
sandwich_orders = ['sandwich_1','sandwich_2','sandwich_3']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print('I made your ' + current_sandwich + '.')
finished_sandwiches.append(current_sandwich)

print('The following sandwiches have been made: \n')
for sandwich in finished_sandwiches:
print(sandwich)
'''

'''
7-9
sandwich_orders = ['pastrami','pastrami','pastrami','sandwich_4']
finished_sandwiches = []

print('The pastrami have been sold out.\n')

while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')

while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print('I made your ' + current_sandwich + '.\n')
finished_sandwiches.append(current_sandwich)

print('The following sandwiches have been made: \n')
for sandwich in finished_sandwiches:
print(sandwich)
'''

'''
7-10
response = {}

polling_active = True

while polling_active:
name = input('\nPlease input your name:	')
place = input('\nIf you could visit one place in the world, where would you go?	')

response[name] = place

repeat = input('\nWould you like to let another people respond(yes/no):	')
if repeat == 'no':
polling_active = False

print('\n-------POLLING RESULTS-------')
for name, place in response.items():
print(name + ' would like to go to ' + place)
'''
  • 点赞
  • 收藏
  • 分享
  • 文章举报
Seal_Wings 发布了44 篇原创文章 · 获赞 0 · 访问量 1143 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐