200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Python编程从入门到实践学习笔记

Python编程从入门到实践学习笔记

时间:2024-04-25 13:28:34

相关推荐

Python编程从入门到实践学习笔记

第2章 变量和简单数据类型

title以首字母大写的方式显示每个单词。lstrip删除字符串左空白,rstrip删除右空白,strip删除两端空白。浮点数计算,0.2+0.3=0.3000000000000004,所有编程语言都可能存在的。python2中3/2=1,python3中3/2=1.5,python2中要保证至少一个为浮点数。

第3章 列表

索引-1可以返回列表最后一个元素。append在列表末尾添加元素,insert在列表指定索引处插入元素。del可以通过索引删除列表元素,也可以直接删除整个列表。pop可以通过索引弹出列表元素,可以弹出列表最后一个元素,返回弹出的元素。remove根据值删除元素。sort对列表进行排序,原列表元素顺序被改变,传递参数reverse=True反向排序。sorted创建新的列表副本进行排序,原列表元素顺序不变。reverse只是反转列表元素的排列顺序,原列表元素顺序被改变。len确定列表长度。

第4章 操作列表

for循环遍历列表,注意缩进。range创建数字范围,左闭右开,range(5)代表0、1、2、3、4,range(1,4)代表1、2、3。要通过list(range(5))的方式创建列表,直接range不是列表。range(1,100,2)中2代表步长。列表解析写法:

squares = [value**2 for value in range(1,11)]print(squares)

切片索引从0开始,取值不包括:右边的索引。不指定切片:左侧索引,则从第一个开始,不指定切片:右侧索引,则终止于列表末尾。[:]的切片写法可以复制列表。列表的元素是可以修改的,元组的元素是不可以修改的。定义元组:

dimensions = (200, 50)

第5章 if语句

in检查特定值是否包含在列表中。if、elif、else语句。if+列表:可以检查列表是否为空。

第6章 字典

字典添加键值对:

alien_0 = {'color': 'green', 'points': 5}print(alien_0)alien_0['x_position'] = 0alien_0['y_position'] = 25print(alien_0)

字典删除键值对:

alien_0 = {'color': 'green', 'points': 5}print(alien_0)del alien_0['points']print(alien_0)

items返回字典键值对列表,遍历字典键值对:

for key, value in user_0.items():print("Key: " + key)print("Value: " + value)

不关心字典键值对的顺序,只跟踪键值对的关联关系。keys返回字典键列表,遍历字典所有键:

for name in favorite_languages.keys():print(name.title())//或for name in favorite_languages:print(name.title())

sorted按顺序遍历字典中的所有键。values返回字典值列表,遍历字典所有值:

for language in favorite_languages.values():print(language.title())

set对字典中的值去重。

第7章 用户输入和while循环

input提示用户输入,输入参数为提示信息,返回结果为用户输入值。input将用户输入解读为字符串。int将字符串转为数字。python2中获取用户输入使用raw_input。务必确保循环可以按预期结束。for循环中不应修改列表,否则会导致难以跟踪其中的元素。

第8章 函数

关键字实参和实参顺序无关,但务必准确指定函数中定义的形参名:

def describe_pet(animal_type, pet_name):"""显示宠物的信息"""print("I have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet(animal_type='hamster', pet_name='harry')

使用参数默认值时,必须先列出没有默认值的形参,再列出有默认值的实参。将列表传递给函数后,在函数中对列表做的修改都是永久性的。如果需要禁止函数修改列表,可以向函数传递列表副本:

function_name(list_name[:])

任意数量实参,实参会封装到一个元组中:

def make_pizza(*toppings):"""概述要制作的比萨,toppings是一个元组"""print("\nMaking a pizza with the following toppings:")for topping in toppings:print("- " + topping)make_pizza('pepperoni')make_pizza('mushrooms', 'green peppers', 'extra cheese')

Making a pizza with the following toppings:- pepperoniMaking a pizza with the following toppings:- mushrooms- green peppers- extra cheese

结合位置实参和任意数量实参:

def make_pizza(size, *toppings):"""概述要制作的比萨"""print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")for topping in toppings:print("- " + topping)make_pizza(16, 'pepperoni')make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Making a 16-inch pizza with the following toppings:- pepperoniMaking a 12-inch pizza with the following toppings:- mushrooms- green peppers- extra cheese

任意数量的关键字实参:

def build_profile(first, last, **user_info):"""创建一个字典,其中包含我们知道的有关用户的一切"""profile = {}profile['first_name'] = firstprofile['last_name'] = lastfor key, value in user_info.items():profile[key] = valuereturn profileuser_profile = build_profile('albert', 'einstein',location='princeton',field='physics')print(user_profile)

{'first_name': 'albert', 'last_name': 'einstein','location': 'princeton', 'field': 'physics'}

使用import导入了整个模块module_name.py,使用其中任何一个函数:

import module_namemodule_name.function_name()

导入模块module_name.py的特定函数:

from module_name import function_0,function_1function_0()function_1()

使用as为导入的模块函数取别名:

from module_name import function_name as fnfn()

使用as为导入的模块取别名:

import module_name as mn

导入模块中的所有函数:

from module_name import *

最佳的做法是,要么只导入需要使用的函数,要么导入整个模块并使用句点表示法。

第9章 类

类名称首字母大写,驼峰命名法,不使用下划线。实例名和模块名都小写,单词之间加上下划线。类的初始化方法__init()__super将子类和父类关联起来,super.__init()__调用父类初始化方法。

第10章 文件和异常

采用with open的方式打开文件:

with open('pi_digits.txt') as file_object:contents = file_object.read()print(contents)

read读取文件全部内容。readlines读取每一行,并存储在一个列表中。写入空文件opem的第二个参数为’w’:

filename = 'programming.txtwith open(filename, 'w') as file_object:file_object.write("I love programming.")

写入( ‘w’)模式打开文件时千万要小心,因为如果指定的文件已经存在, Python将在返回文件对象前清空该文件。以附加( ‘a’)模式打开文件时, Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。try-except-else代码块,try代码块执行成功时才运行else代码块。split默认以空格分割字符串,可以统计单词个数。pass什么也不做,可以充当占位符。json.dump()存储json数据:

import jsonnumbers = [2, 3, 5, 7, 11, 13]filename = 'numbers.json'with open(filename, 'w') as f_obj:json.dump(numbers, f_obj)

json.load()读取json数据:

import jsonfilename = 'numbers.json'with open(filename) as f_obj:numbers = json.load(f_obj)print(numbers)

第11章 测试代码

导入模块unittest和要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试:

def get_formatted_name(first, last):"""Generate a neatly formatted full name."""full_name = first + ' ' + lastreturn full_name.title()

import unittestfrom name_function import get_formatted_nameclass NamesTestCase(unittest.TestCase):"""测试name_function.py"""def test_first_last_name(self):"""能够正确地处理像Janis Joplin这样的姓名吗? """formatted_name = get_formatted_name('janis', 'joplin')self.assertEqual(formatted_name, 'Janis Joplin')unittest.main()

assertEqual断言方法,判断结果和预期是否一致。测试方法要以test_打头,将自动运行。如果你在TestCase类中包含了方法setUp(), Python将先运行它,再运行各个以test_打头的方法。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。