Python编程:从入门到实践
文章目录
Prat 1 基础知识
第一章 起步
Now is better than never.
第二章 变量和数据类型
变量的命名和使用:慎用小写字母l和大写字母O,因为它们可能被看错成数字1和0
- 数与运算
print(2 ** 3) # **表示乘方
print(2.0 ** 3) # 运算时只要有浮点数,结果一定是浮点数
print(4/2) # 任意两个数相除,结果一定是浮点数
print(100_000_000) # 可以使用_将大数字分组,Python会忽略其,仅在3.6或更高版本支持第三章 内置函数
| 内置函数 | |
|---|---|
| title() | 首字母大写 |
| format() | 格式化函数 |
- format() 格式化函数
first_name = "hello"
last_name = "world"
full_name_1 = "{1} {0}".format(first_name, last_name)
full_name_2 = f"{first_name.title()} {last_name}" # f字符串是Python3.6引入的;title()方法不会改变变量的值
print(sum(list_c)) # 列表、元祖求和- sorted() 临时排序、sort() 永久排序
fruit_list = ["Apple", "Pear", "Orange", "Banana", "Mango"]
sorted(fruit_list)
print(fruit_list) # ['Apple', 'Pear', 'Orange', 'Banana', 'Mango']
return_rel = fruit_list.sort(reverse=True)
print(fruit_list) # ['Pear', 'Orange', 'Mango', 'Banana', 'Apple']
print(type(return_rel)) # <class 'NoneType'>- reverse() 临时反转、reversed() 永久反转
c = reversed(a) # reversed(a)并不会改变a的值
b.reverse() # b.reverse()会修改b的值
print(type(c)) # <class 'list_reverseiterator'>
print(tuple(c)) #(2, 4, 3, 1)
print(list(c)) #[] c已经被遍历结束,无新的值可以转换为list第四章 列表
del fruit_list[3] # 指定索引,删除item
fruit_list.pop(1) # 指定索引,删除item,并返回删除的item;无参数时,删除最后一个元素
fruit_list.remove("Apple") # 指定item,进行删除;remove()只删除第一个满足条件的值
list_c = [ num**2 for num in range(6) if num%2==0] # 列表解析
list("abcdefg") # 转换为列表
list(range(1,6))
list_1[:] # 列表复制第五章 元祖
tuple_1(1,) # 元祖只有一个值时,必须后面加上逗号;否则视为单个元素,而不是元祖第六章 字典
键值:键必须为字符串,值可以是数字、列表、元祖、字典
在Python 3.7中,字典中元素的排列顺序与定义时相同,如果将字典打印出来或遍历其元素,将发现元素的排列顺序与添加顺序相同。
del dict_1['name']
dict_2.get('school','cannot find key named school in this dict') # 可以使用get(),在指定键不存在时,返回一个默认值
for k,v in dict_3.items()
for k in dict_4.keys() # dict_4.keys() 的类型为:<class 'dict_keys'>第七章 集合
不同于列表和字典,集合不会以特定的顺序存储元素,且集合中的每个元素都是第一无二的。
for language in set(favorite_languages.values()) # 使用set(),剔除重复项第八章 循环
continue:让Python忽略余下的代码,并返回循环的开头,继续之后的循环
break:中断结束所有的循环
while True:
pass # 无限循环,设置条件退出Part 2 函数、类、方法
类中的函数成为方法
- 传递任意数量的实参
形参名 *toppings 中的星号,让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。
- 传递任意数量的关键字实参
形参**user_info中的两个星号,让Python创建一个名为user_info的空字典,并将收到所有值都放在这个字典中。
Part 3 封装、继承、多态
模块是扩展名为.py的文件
假设Car类有一个名为fill_gas_tank()的方法,它对全电动汽车来说毫无意义,因此你可能想重写它。使用继承时,可以放子类保留从父类那里继承而来的精华,并提出不需要的糟粕。
class ElectricCar(Car):
def fill_gas_tank(self):
"""电动汽车没有邮箱"""
print("This car doesnot need a gas tank!")可以在一个A类中,将一个B类实例作为A类的属性,如 self.battry = Battry()
Part 4 异常
依赖try代码块成功执行的代码都应放到else代码块中
其他
可以在变量定义的时候,进行注释说明
内置序列类型:字符串、列表、元祖
序列类型支持:索引、切片、拆包
切片 [起始下标 : 结束下标 : 步长]
# Example:
list_1[::-1] # 列表反向输出,结果类型为:<class 'list'>replace(old, new, count)
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论