《Python编程:从入门到实践》学习笔记II

第六章 字典

6.1 简单的字典

alien = {'color': 'green', 'points': 5}
print(alien['color'])     # green
print(alien['points'])    # 5

6.2 使用字典

字典就是一系列键值对,每个键都能找到对应的值,python中任何对象都可以成为。字典用{}来表示

# 访问键值对
alien = {'color': 'green'}
print('the color of alien is ' + alien['color'])

# 添加键值对
alien['x_position'] = 0
alien['y_position'] = 25
print(alien)

其他操作

# 创建一个空字典
# 用字典来存储用户提供的数据/编写能自动生成大量键值对代码时
# 通常需要先定义一个空字典
alien_0 = {}
alien_0['color'] = 'purple'
alien_0['points'] = 7
print(alien_0)

# 修改字典中的值
print('the color before is: ' + alien_0['color'])
alien_0['color'] = 'yellow'
print('the color after is: ' + 
      alien_0['color'])

# 删除键值对
print(alien_0)
del alien_0['points']
print(alien_0)

如果要输出的内容太多,print输出是可以换行的

6.3 遍历字典

可以遍历所有键值对,或者所有, 或者所有

user = {
    'username': 'jack',
    'first': 'google',
    'last': 'steam'
}
# 遍历所有键值对
for key, value in user.items():
    print('\nkey:' + key)
    print('value:' + value)

# 遍历所有键
# 遍历字典时,默认遍历所有的键。不写.keys()输出结果不变,但是这种写法可读性更强
for x in user.keys():
    print(x.title())
print('\n')

# 按顺序遍历所有键
for x in sorted(user.keys()):
    print(x.title())
print('\n')

# 遍历所有值
for y in user.values():
    print(y)

提取字典中所有值的时候,可能会出现大量重复元素,为了剔除重复,可以用集合(set)。比如说:

for x in set(user.values()):
    print(x)

6.4 嵌套

有列表套字典,字典套列表,字典套字典

# 字典列表
aliens = []
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5}
    aliens.append(new_alien)

# 在字典中存储列表
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese']
}

# 在字典中存储字典
users = {
    'userA': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'new york',
    },

    'userB': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    },
}

第七章 用户输入和while循环

7.1 input()工作原理

input()让程序暂停运行,接受一个输入后再继续运行。

age = int(input("how old are you?"))
if age >= 18:
    print("you're an adult!")
else:
    print("you're a child")
  • int():input()默认接受的是字符串,所以进行数字大小比较的时候应该用int()来进行类型转换。
  • 求模运算符%:返回的是余数

7.2 while循环简介

可以让用户选择何时退出

message = ""
while message != 'quit':
    message = input("say something, if you want to quit, enter quit\n")
    if message != 'quit':
        print(message)

可以设置标志——用于判断整个程序是否处于活动状态。简化了while语句,只要任何一个条件使active变成了False,while就结束。

active = True
while active:
    message = input('say something:\n')

    if message == 'quit':
        active = False
    else:
        print(message)

也可以用break打破循环

7.3 使用while循环来处理列表和字典

在列表之间移动元素

unconfirmed = ['alice', 'jack', 'tony']
confirmed = []

while unconfirmed:    # 将未确认的列表移入确认列表
    current = unconfirmed.pop()    # 储存临时变量
    print('verifying user:' + current.title())
    confirmed.append(current)

print('\nfollowing users have been verified:')
for x in confirmed:
    print(x.title())

删除所有特定值

pets = ['dog', 'cat', 'dog', 'dog', 'dog', 'cat']

while 'cat' in pets:
    pets.remove('cat')
print(pets)

第八章 函数

8.1 定义函数

函数是带名字的代码块,负责具体功能实现。username形参,jesse实参(调用函数时传递的参数)

def greet(username):
    print('hello ' + username.title() + '!')
greet('jesse')

8.2 传递实参

位置实参。顺序很重要,如果位置不正确,输出结果可能有问题。

def pet(pet_type, name):
    print('i have a ' + pet_type)
    print('its name is ' + name)

pet('dog', 'jack')

关键字实参。务必准确指定函数定义中的形参名。也可以设置默认值

def pet(pet_type, name='dog'):    # 可以设置默认值
    print('i have a ' + pet_type)
    print('its name is ' + name)

pet(pet_type='dog', name='jack')

8.3 返回值

# 返回字典
def build_person(firstname, lastname):
    person = {'first': firstname, 'last': lastname}
    return person

musician = build_person('jimi', 'swift')
print(musician)

8.4 传递列表

# 传递列表
def greet(names):
    for x in names:
        print('hello ' + x )

username = ['lily', 'jack', 'tony']
greet(username)

# 禁止函数修改列表
# 切片法[:]创建列表的副本,只对副本做改变,不影响原件
greet(username[:])

8.5 传递任意数量的实参

传递任意数量的实参 。*toppings创建一个名为toppings的空元组,并将所有收到的值封装在这个元组中。

def make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

使用任意数量的关键字实参

def build_profile(first, last, **user_info):
    profile = {}    # 空字典
    profile['first'] = first
    profile['last'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile(
    'taylor', 'swift',
    location='new york',
    field='musician'
)

print(user_profile)
  • **user_info两个星号让python创建一个空字典,并将收到的所有键值对封装在这个字典中。
  • 一个星号*-->空元组;两个星号**-->空字典

8.6 将函数存储在模块中

函数可以将代码块和主程序进行分离。

# 导入整个模块
# 写一个pizza.py文件,里面是定义好的函数
import pizza
pizza.make_pizza(16, 'mushrooms')

# 导入特定的函数
from module_name import  function_name

# 使用as给函数指定别名
from module_name import function_name as fn

# 使用as给模块指定别名
import  module_name as mn

# 导入模块中所有的函数
from module_name import *

第九章 类

9.1 创建和使用类

class Dog():
    def __init__(self, name, age):
        self.name = name    # 属性
        self.age = age

    def sit(self):    # 方法
        print(self.name.title() + 'is now sitting.')

    def roll_over(self):
        print(self.name.title() + 'rolled over!')
  • 类中的函数称为方法__init__是一个特殊的方法,每当Dog类创建新实例时,都会自动运行它。形参self必不可少,且位于其他形参前面。[有关__init__的解释](Python中 __init__的通俗解释是什么? - 初识CV的回答 - 知乎 https://www.zhihu.com/question/46973549/answer/1682758202)
  • 为何必须包含self:它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。且__init__创建Dog时,会自动传入实参self
  • 属性调用和方法调用都可以用.的方法。

根据类创建实例

my_dog = Dog('jack', 6)

print("My dog's name is " + my_dog.name.title() + '.')
print("My dog is " + str(my_dog.age) + "years old.")

9.2 使用类和实例

9.3

posted @ 2022-08-04 18:05  mi4444ta  阅读(62)  评论(0)    收藏  举报