Python3 学习笔记
1.基础语法
1.1 字符串操作
- title() 将单词首字母改为大写
- upper() 所有字母改为大写
- lower() 所有字母改为小写
- str1+str2 字符串通过’+'拼接
- rstrip,lstrip,strip 去除字符串前、后、两端空白
1.2 数字、浮点数
- =、-、*、/ 加减乘除
- a**b a的b次方
注意:
age = 23
message = "Happy " + age + "rd Birthday!"
代码将引发错误,系统不知道age表示数值23还是字符2和3,可以使用str()函数,让Python将age整数用作字符串
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
1.3注释
在Python中,注释用井号(#)标识。井号后面的内容都会被Python解释器忽略
2.列表
类似于其他编程语言中的数组,索引从0开始
例如:
bicycles = ['trek', 'cannondale', 'redline', 'specialized'];
Python提供的一种方法。通过将索引指定为-1可让Python返回最后一个列表元素
负数索引返回离列表末尾相应距离的元素
2.1列表简介
#定义一个数组
list=['机器学习','人工智能','深度学习'];
2.1.1 修改操作
list[0]='卷积神经网络';
2.1.2 添加操作
- 在列表末尾添加元素
list.append('ducati');
- 在列表任意位置添加元素
#第一个参数代表添加位置,第二个参数为添加元素
list.insert(0,'ducati');
2.1.3 删除操作
- 删除列表中第n个元素
#删除列表中第n+1个元素
del list[n]
- pop函数
#删除列表末尾,并获取值
end=list.pop();
#删除指定索引元素,并获取值
end=list.pop(0);
- 根据值删除元素
#只删除出现的第一个值
list.remove('机器学习');
2.2 组织列表
2.2.1 列表排序
- sort 函数进行永久排序
#正序排列
list.sort();
#逆序排序 只需向sort()方法传递参数 reverse=True
cars.sort(reverse=True)
- sorted函数对列表临时排序
#sorted 只是返回一个排序后的列表不改变原列表的顺序
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
- 反转列表
list.reverse();
- 确定列表长度
len(list);
3.列表操作
3.1遍历列表
#定义一个列表
magicians = ['alice', 'david', 'carolina'];
3.1.1 for循环
# 每次for循环会执行索引有缩进的语句
for magician in magicians:
print(magician);
3.2 数值列表的创建
3.2.1 range()函数
#使用range函数循环打印一个范围内数字
for num in range(1,5):
print(num);
#range函数可以指定 步长
#list函数可以将range函数转化为列表
numbers = list(range(1,6))
print(numbers)
3.2.2 简单统计函数
digits=[1,2,3,4,5,6,7,8,9,0]
#取最小
min(digits)
#取最大
max(digits)
#求和
sum(digits)
3.2.3 列表解析
list=[value**2 for value in range(1,6)]
3.3 使用列表的一部分
3.3.1 切片
处理列表的部分元素——Python称之为切片
例子:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
#结果 ['charles', 'martina', 'michael']
#如果不指定开始元素默认从头开始提取
print(players=[:4])
#返回后三位
print(player[-3:])
3.3.2 遍历切片
for(value int list[0:3])
3.3.3 复制列表
先看一个例子
#先创建两个数组,直接赋值
my_food=['apple','banala','panda']
food=my_food
结果发现直接赋值,相当于给数组my_food起了个别名,并未创建新的数组
Python数组复制方法
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('apple')
print(my_foods)
print(friend_foods)
注意:python中数组复制要使用切片的方式
3.4 元组
有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表被称为元组。
3.4.1 定义元组
#定义元组将定义列表的[]改为()就好
dimensions=(200,50)
#因为元组元素是不可变,要修改元组只能重新定义元组
dimensions=(400,40)
4.IF
4.1 条件测试
a=1
b=2
#等于判断
a==b
#不相等判断
a!=b
#小于、大于、大于等于、小于等于
a<b;
a>b;
a<=b;
a>=b;
#多个条件时用 and和or链接
a>b and a!=0
#检查特定值是否在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings;
#检查特定值是否不在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
5.字典
5.1 字典操作
#定义字典 类似Map
alien={'color':'green','points':5}
print(alien['color']);
#创建空白字典
alien={};
#添加键值对
alien['color']='green';
alien['points']=5;
print(alien['color']+" "+str(alien['points']))
#修改键值对的值
alien['color']='yellow'
#删除键值对
del alien['color']
5.2字典遍历
#遍历字典键值对
alien={'color':'green','points':5}
for key,value in alien.items():
print("\nkey:"+key)
print("value:"+str(value))
#遍历字典键
for name in alien.keys():
print("\nname:"+name)
#按顺序遍历字典键
for name in sorted(alien.keys()):
print("\nname:"+name)
#遍历所有值
for name in alien.values():
print("\nname:"+name)
5.4 嵌套
#字典数组
alien_0={'color':'green','points':5}
alien_1={'color':'red','points':5}
alien_2={'color':'blue','points':5}
alien_3={'color':'yellow','points':5}
aliens={alien_0,alien_1,alien_2,alien_3}
for alien in aliens:
print(alien)
6.用户输入与while循环
6.1用户输入
6.1.1 input()
作用:让程序暂停运行,等待用户输入一些文本
#获取用户输入
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
6.1.2 int()
从input获取的数值默认为字符串,通过int()强制转换为数值类型
age = input("How old are you ")
age=int(age)
print(age)
6.2 while循环
n=0
while n<=5:
print(n)
n+=1
#break 可以退出循环
#continue 进行下一次循环
7.函数
7.1 函数定义:
def solution():
"""显示简单问候语"""
print("hellow word")
solution()
#文档字符串用三引号括起,Python使用它们来生成
#关键字实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
#关键字实参与顺序无关
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')
#这样调用函数会生成列表副本,不会影响原来的列表
print_models(unprinted_designs[:], completed_models)
#传递任意数量的实参
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
7.2 导入函数模块
7.2.1 导入整个模块
#导入同文件夹下的pizz
import pizz
pizz.make_pizza(16, 'pepperoni')
pizz.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
7.2.2 导入特定函数
from module_name import function_0, function_1, function_2
7.2.3 别名
#函数别名
from module_name import function_0 as fn
#给模块起别名
import pizza as p
7.2.4 导入模块中所有函数
#大型模块中不建议这么做,容易因为函数名相同,导致函数覆盖
from pizza import *
8. 类
8.1 创建和使用类
class Dog():
"""创建一个小狗类"""
#构造函数 self会自动传递 我们只需要给出name和age
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!")
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
注意init两端各有两个_
8.2 继承
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def describe(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
class ElectricCar(Car):
"""电动汽车"""
def __init__(self,make,model,year):
"""初始化父类"""
super().__init__(make,model,year)
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.describe())
8.3 导入模块
#导入一个类
from car import Car
#导入多个类
from car import Car,ElectricCar
#导入整个模块
import car
#导入模块中所有类(不推荐使用)
from car import *
8.4 python 标准库
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")