学习日记之《python编程从入门到实践》


笔记为主,按照原书的目录按需记录

第二章——变量和简单数据类型

2.2.1 变量的命名和使用

  1. 变量名只能包含字母数字和下划线,不能以数字打头
  2. 变量名不能包含空格
  3. 不能将python关键字和函数名作为变量名
  4. 变量名应简短且有描述性
  5. 慎用小写的 l 和大写字母 O
  6. 全大写的变量视为常量,值不变

2.3 字符串

字符串的常用方法
name = 'ada lovelace'
name.title()  # 首字母大写
name.upper()  # 全部大写
name.lower()  # 全部小写
name.strip()  # 删除两端空白
name.rstrip()  # 删除右侧空白
name.lstrip()  # 删除左侧空白
title = "Alice in wonderland“
title_list = title.split()  # 将字符串按照指定内容分割成列表,默认是空格

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!

第三章——列表简介

3.2 列表的常用方法

list_it = ['a', 'b', 'c']
list_it.append(‘d’)   # 在原列表末尾添加新元素d
list_it.insert(0, 'd')  # 在索引0处添加新元素d
del list_it[0]   # 删除列表内索引为0的元素
poped = list_it.pop()   # 删除列表末尾的元素,并将其返回
poped = list_it.pop(0)  # 删除列表内索引为0的元素,并将其返回
list_it.remove('a')  # 按元素值删除元素,只删除第一个指定的值
list_it.sort()  # 对列表排序
list_it.sort(reverse=True)  # 对列表反排序
sort_it = sorted(list_it)  # 对原列表临时排序,并不影响原列表的顺序,可加reverse=True
list_it.reverse()  # 将原列表反序

第四章——操作列表

digits = [1,2,3,4,5]
min(digits)
max(digits)
sum(digits)

列表解析式
squares = [values **2 for value in range(1,11)]  # 还可以加if语句

复制列表

# 1、通过切片复制
list_a = ['a', 'b', 'c']
list_b = list_a[:]

list_a.append(1)
list_b.append(2)

print(list_a)  # ['a', 'b', 'c', 1]
print(list_b)  # ['a', 'b', 'c', 2]
注意这样操作不是复制,两个变量指向同一个列表
list_a = ['a', 'b', 'c']
list_b = list_a

list_a.append(1)
list_b.append(2)

print(list_a)  # ['a', 'b', 'c', 1, 2]
print(list_b)  # ['a', 'b', 'c', 1, 2]
浅复制:原数据中没有可变数据结构
1、这样类似于切片复制
list_a = ['a', 'b', 'c']
list_b = list_a.copy()

list_a.append(1)
list_b.append(2)

print(list_a)  # ['a', 'b', 'c', 1]
print(list_b)  # ['a', 'b', 'c', 2]

2、原数据中有可变的数据结构,修改该数据结构会影响到另一个数据
list_a = ['a', 'b', 'c', [1,2,3]]
list_b = list_a.copy()

list_a[3].append(4)

print(list_a) # ['a', 'b', 'c', [1, 2, 3, 4]]
print(list_b) # ['a', 'b', 'c', [1, 2, 3, 4]]

3、不修改可变的数据结构,则不会影响另一个数据
list_a = ['a', 'b', 'c', [1,2,3]]
list_b = list_a.copy()

list_a.append(4)

print(list_a)  # ['a', 'b', 'c', [1, 2, 3], 4]
print(list_b)  # ['a', 'b', 'c', [1, 2, 3]]

深复制:是指创建一个新对象,并且这个新对象与原始对象没有任何关联。
也就是说,在新对象中,原始对象中的所有元素都被复制到了新的内存地址中。
如果原始对象中的元素发生了变化,那么新对象中的元素不会受到影响。
import copy

list_a = ['a', 'b', 'c', [1,2,3]]
list_b = copy.deepcopy(list_a)

list_a[3].append(4)

print(list_a)  # ['a', 'b', 'c', [1, 2, 3, 4]]
print(list_b)  # ['a', 'b', 'c', [1, 2, 3]]

第六章——字典

example_dict = {'name':'cooper', 'age':18}
del example_dict['name']   # 删除键值对

name = example_dict.get('name', 'no this key')  # get()方法获取指定键

遍历字典

遍历键值对
example_dict = {'name':'cooper', 'age': 18, 'state': 'China'}

for key, value in example_dict.items():
    print(key, value)   
# name cooper
# age 18
# state China

遍历字典的键:
example_dict = {'name':'cooper', 'age': 18, 'state': 'China'}

example_list = example_dict.keys()
print(example_list)  # dict_keys(['name', 'age', 'state'])

for key in example_dict.keys():
    print(key)
# name
# age
# state

遍历字典的值
example_dict = {'name':'cooper', 'age': 18, 'state': 'China'}

example_list = example_dict.values()
print(example_list)  # dict_values(['cooper', 18, 'China'])

for value in example_dict.values():
    print(value)  
# cooper
# 18
# China

第七章——用户输入和While循环

删除列表中的特定值
example_list = ['a', 'b', 'c', 'a']

while 'a' in example_list:
    example_list.remove('a')

print(example_list)  # ['b', 'c']

第八章——函数

位置实参和任意数量的实参
def f(name, *args):
    print(name, args, type(args))

f('cooper', 'age', 'state')  # cooper ('age', 'state') <class 'tuple'>

位置实参和任意数量的关键字实参
def f(name, **kwargs):
    print(name, kwargs, type(kwargs))

f('cooper', age='age', state='state')  # cooper {'age': 'age', 'state': 'state'} <class 'dict'>

== import 函数或者模块的时候,可以使用 as 对其指定别名 ==

第十章——文件和异常

读取整个文件
file = 'read.txt'
with open(file, mode='r') as f:
    contents = f.read()
print(repr(contents))  # 'name=cooper\nage=18\nstate=China\n'

逐行读取
file = 'read.txt'
with open(file, mode='r') as f:
    for line in f:
        print(repr(line))
# 'name=cooper\n'
# 'age=18\n'
# 'state=China\n'

创建一个包含文件各行内容的列表
file = 'read.txt'
with open(file, mode='r') as f:
    lines = f.readlines()

print(lines)  # ['name=cooper\n', 'age=18\n', 'state=China\n']

python只能将字符转内容写入文本文件

103.3 处理异常

while True:
    first_number = input("\nFirst Number:")
    if first_number == 'q':
        break

    second_number = input("\nSecond Number:")
    if second_number == 'q':
        break

    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print(f"second_number:{second_number}, 不能为0")
    else:
        print(f'答案为{answer}')
    finally:
        print('retry')

10.4、json模块之存储数据

1、将内容以json格式写入到文件中
import json

numbers = [1,2,3,4,5]
filename = 'numbers.json'
with open(filename, 'w') as f:
    json.dump(numbers, f)

2、读取json格式的文件
import json

filename = 'numbers.json'
with open(filename, 'r') as f:
    numbers = json.load(f)

print(numbers, type(numbers))  # [1, 2, 3, 4, 5] <class 'list'>

3、将字典数据转化为字符串
import json

example_dict = {'name': 'cooper', 'age':18}

json_dumps = json.dumps(example_dict)
print(json_dumps, type(json_dumps)) # {"name": "cooper", "age": 18} <class 'str'>

4、将字符串转化为原格式,字符串内饰列表就转化为列表,是字典就转化为字典(内部要使用双引号)
import json

example_dict = '{"name": "cooper", "age":18}'

json_dumps = json.loads(example_dict)
print(json_dumps, type(json_dumps)) # {'name': 'cooper', 'age': 18} <class 'dict'>

10.4.3之重构

一个样例

import json

def get_stored_username():
    '''如果存储了用户名就获取'''
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def initialize_json():
    '''初始化json文件'''
    filename = 'username.json'
    initial_data = {'name': []}
    with open(filename, 'w') as f:
        json.dump(initial_data, f)

def put_new_username(newuser):
    '''将新用户放入文件中'''
    filename = 'username.json'
    with open(filename) as f:
        name_data = json.load(f)
    name_data['name'].append(newuser)
    with open(filename, 'w') as f:
        json.dump(name_data, f)
    print(f"We'll remember when you come back, {newuser}")

def greet_user():
    '''问候用户并指出其名字'''
    initialize_json()
    while True:
        input_name = input("请输入你的用户名:")
        input_name = input_name.strip()
        username = get_stored_username()
        if input_name in username['name']:
            print(f"welcome back, {input_name}")
        else:
            put_new_username(input_name)

greet_user()

第十一章——测试代码

import unittest

from Module_Test import get_formatted_name

class NameTestCase(unittest.TestCase):  # 测试类必须继承 unittest.TestCase
    
    def setUp(self) -> None:
        '''只需创建对象一次,即可在所有测试方法中使用,
        可在此创建实例并设置其属性
        '''
        pass

    def test_first_last_name(self):   # test_开头的方法会自动运行
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplined')


if __name__ == "__main__":
    unittest.main()
  1. 测试类必须继承 unittest.TestCase
  2. test_开头的方法会自动运行
  3. setUp()方法可存放实例及其属性
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值