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

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

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

第3章 列表

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

第4章 操作列表

  1. for循环遍历列表,注意缩进。
  2. range创建数字范围,左闭右开,range(5)代表0、1、2、3、4,range(1,4)代表1、2、3。
  3. 要通过list(range(5))的方式创建列表,直接range不是列表。
  4. range(1,100,2)中2代表步长。
  5. 列表解析写法:
squares = [value**2 for value in range(1,11)]
print(squares)
  1. 切片索引从0开始,取值不包括:右边的索引。
  2. 不指定切片:左侧索引,则从第一个开始,不指定切片:右侧索引,则终止于列表末尾。
  3. [:]的切片写法可以复制列表。
  4. 列表的元素是可以修改的,元组的元素是不可以修改的。
  5. 定义元组:
dimensions = (200, 50)

第5章 if语句

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

第6章 字典

  1. 字典添加键值对:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
  1. 字典删除键值对:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
  1. items返回字典键值对列表,遍历字典键值对:
for key, value in user_0.items():
    print("Key: " + key)
    print("Value: " + value)
  1. 不关心字典键值对的顺序,只跟踪键值对的关联关系。
  2. keys返回字典键列表,遍历字典所有键:
for name in favorite_languages.keys():
    print(name.title())
//for name in favorite_languages:
    print(name.title())
  1. sorted按顺序遍历字典中的所有键。
  2. values返回字典值列表,遍历字典所有值:
for language in favorite_languages.values():
    print(language.title())
  1. set对字典中的值去重。

第7章 用户输入和while循环

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

第8章 函数

  1. 关键字实参和实参顺序无关,但务必准确指定函数中定义的形参名:
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')
  1. 使用参数默认值时,必须先列出没有默认值的形参,再列出有默认值的实参。
  2. 将列表传递给函数后,在函数中对列表做的修改都是永久性的。
  3. 如果需要禁止函数修改列表,可以向函数传递列表副本:
function_name(list_name[:])
  1. 任意数量实参,实参会封装到一个元组中:
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:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
  1. 结合位置实参和任意数量实参:
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:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
  1. 任意数量的关键字实参:
def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein',
'location': 'princeton', 'field': 'physics'}
  1. 使用import导入了整个模块module_name.py,使用其中任何一个函数:
import module_name
module_name.function_name()
  1. 导入模块module_name.py的特定函数:
from module_name import function_0,function_1
function_0()
function_1()
  1. 使用as为导入的模块函数取别名:
from module_name import function_name as fn
fn()
  1. 使用as为导入的模块取别名:
import module_name as mn
  1. 导入模块中的所有函数:
from module_name import *
  1. 最佳的做法是,要么只导入需要使用的函数,要么导入整个模块并使用句点表示法。

第9章 类

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

第10章 文件和异常

  1. 采用with open的方式打开文件:
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)
  1. read读取文件全部内容。
  2. readlines读取每一行,并存储在一个列表中。
  3. 写入空文件opem的第二个参数为’w’:
filename = 'programming.txt
with open(filename, 'w') as file_object:
    file_object.write("I love programming.")
  1. 写入( ‘w’)模式打开文件时千万要小心,因为如果指定的文件已经存在, Python将在返回文件对象前清空该文件。
  2. 附加( ‘a’)模式打开文件时, Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。
  3. try-except-else代码块,try代码块执行成功时才运行else代码块。
  4. split默认以空格分割字符串,可以统计单词个数。
  5. pass什么也不做,可以充当占位符。
  6. json.dump()存储json数据:
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
  1. json.load()读取json数据:
import json
filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)

第11章 测试代码

  1. 导入模块unittest和要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试:
def get_formatted_name(first, last):
    """Generate a neatly formatted full name."""
    full_name = first + ' ' + last
    return full_name.title()
import unittest
from name_function import get_formatted_name
class 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()
  1. assertEqual断言方法,判断结果和预期是否一致。
  2. 测试方法要以test_打头,将自动运行。
  3. 如果你在TestCase类中包含了方法setUp(), Python将先运行它,再运行各个以test_打头的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yyz0300

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值