Python学习记录——推荐网站与基础知识
python基础学习记录
推荐的学习网站
官网:https://www.python.org/
菜鸟教程:https://www.runoob.com/
W3school:https://www.w3school.com.cn/
廖雪峰的官网:https://www.liaoxuefeng.com/
知乎:https://www.zhihu.com/
stackoverflower:https://stackoverflow.com/
IDE
Pycharm ,破解使用最新架包,不然会出现使用一段时间闪退的情况。可以自行搜索方法。
基础知识的学习
参考书籍
Python编程从入门到实践
变量与简单数据类型
输出:print
字符串:双引号或单引号括起来
修改字符串大小写的函数:
str.title():首字母大写
str.upper:全大写
str.lower:全小写
合并字符串:
str1="hello"
str2="world"
str=str1+" "+str2
制表符:\t
换行符:\n
print("Language:\n\tPython\n\tC")
输出:
Language:
Python
C
删除空白(暂时删除,不改变原str):
末尾空白:str.rstrip()
前端空白:str.lstrip()
两端空白:str.strip()
乘方:**
a的b次方: a**b
类型转化 str():
age = 10
print("Happy "+str(age)+"rd Birthday!")
列表
Python中用[]表示列表,其中的元素用逗号分隔例如:
pets = ['dog' ,'cat' ,'rabbit']
访问列表元素(下标从0开始):
print(pets[0])
访问列表最后元素:
print(pets[-1])
修改元素:
pets[2] = 'fish'
添加元素:
1.末尾添加(append函数):
pets.append('bird')
2.插入(insert函数,第一个参数表示插入位置,原列表元素后移):
pets.insert(0, 'bird')
此时列表元素为 ['bird', 'dog' ,'cat' ,'rabbit']
删除元素:
del(), pop(), remove()区别:
del()删除:
del pets[-1]
pop()删除可使用删除值():
无参数默认最后一个(学过栈应该了解,但这里pop()可以弹出任意位置)
poped_pet = pets.pop()
此时pets末尾元素删除,poped_pet = 'rabbit'
poped_pet = pets.pop(0)
此时pets末尾元素删除,poped_pet = 'bird'
remove()可以根据值删除:
例如:pets.remove('cat')
排序:永久排序,临时排序,倒着打印(原列表 [‘bird’, ‘dog’ ,‘cat’ ,‘rabbit’])
pets.sort():默认永久正序,按字母顺序,['bird', 'cat' ,'dog' ,'rabbit']
pets.sort(True):永久倒序,按字母顺序
print(sorted(pets)):打印排序后的列表,原pets列表不变
pets.reverse():倒着打印,而不是按字母顺序, ['rabbit', 'cat', 'dog', 'bird']
确定列表长度:len()
print(len(pets))
操作列表
1.循环(注意缩进与冒号)
language = ['python', 'c', 'c++', 'java']
for i in language:
print('hello '+i + '!')
2.range()函数:
# range函数(打印1-5)
for value in range(1, 6):
print(value)
3.range创建列表
# 创建数值列表(list函数加range函数)
numbers = list(range(1, 6))
print(numbers)
# 创建数值列表(1-10,偶数)
even_num = list(range(2, 11, 2))
print(even_num)
# 创建平方列表
squares = []
for i in range(1, 11):
squares.append(i**2)
print(squares)
4.数字列表统计
# 数字列表统计
print(min(squares))
print(max(squares))
print(sum(squares))
5.列表解析
# 列表解析,打印1-10的平方
digits = [i**2 for i in range(1, 11)]
print(digits)
6.切片的使用
# 切片(打印m-n个元素,切片(m-1,n))
numbers=list(range(1, 11))
print(numbers)
# 打印4-6
print(numbers[3: 6])
# 打印3-最后
print(numbers[2:])
# 从开始到5
print(numbers[: 5])
# 打印最后4个
print(numbers[-4:])
# 打印除了最后4个之外的
print(numbers[:-4])
# 遍历切片
for i in numbers[:5]:
print(i)
# 列表复制(单独分配地址,两个列表独立)
num1 = [i for i in range(1, 6)]
num2 = num1[:]
num1.append(100)
num2.append(101)
print(num1)
print(num2)
7.判断列表是否为空
# 判断列表是否为空
num4 = []
if num4:
print("not null")
else:
print("null")
8.元组
# 元组元素不可修改,但可以重定义元组
num3 = (1, 2)
print(num3)
num3 = (3, 4)
print(num3)
if语句
注意==,>=, <=最好两边加等号
c,c++语言中是if_else if_else,python else if是elif,后面有冒号
例如:
age = 12
if age < 4:
print("cost $0.")
elif age < 18:
print("cost $5.")
else:
print("cost $10.")
字典
在python中,字典是一系列的键值对,可以通过键来访问对应的值
例如:
alien_0 = {'color': 'red', 'point': 5}
color:red ,point:5就是两对键值对
创建字典:
# 创建字典,键值对
alien_0 = {}
alien_0['color'] = 'green','red'
alien_0['points'] = 5
print(alien_0)
删除键值对
# 删除键值对
del alien_0["points"]
遍历键值对,遍历键值对:items(),遍历值:values(),遍历键 :keys(),pycharm输入首字母会出现一系列的方法。
# 创建字典
favorite_language = {}
favorite_language['A'] = 'java'
favorite_language['B'] = 'python'
favorite_language['C'] = 'c'
# 遍历键值对
for name,language in favorite_language.items():
print('\nname: ' + name)
print('language: ' + language.title())
# 遍历键keys(),遍历值values()
print('\nAll keys:')
for name in favorite_language.keys():
print(name.title())
字典,列表的嵌套使用
1.字典存列表
# 字典存列表
favorite_language = {
'A': ['C', 'Python'],
'B': ['Java']
}
for name , languages in favorite_language.items():
print(name+': ')
for language in languages:
print('\t'+language)
2.列表存字典
# 列表存字典
alien_0 = {'color': 'red', 'point': 5}
alien_1 = {'color': 'green', 'point': 10}
alien_2 = {'color': 'yellow', 'point': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
3.字典存字典
# 字典存字典
aliens = {
'alien_0': {
'color': 'red',
'point': 5
},
'alien_1': {
'color': 'green',
'point': 10
},
}
for alien_num, alien_info in aliens.items():
print('alien_num: '+ alien_num)
print('\t' + alien_info['color'])
print('\t' + str(alien_info['point']))
用户输入与While循环
用户输入
input()函数:让程序暂停,等待用户输入,python将输入内容存储到一个变量里
int():类型转化,可转化为数值
%:求模
例子:判断输入整数奇偶
# 用户输入
number = input("please input a number ,tell you even or odd?:")
number = int(number)
if number % 2==0:
print(str(number)+"is even!")
else:
print(str(number) + " is odd!")
while循环(for循环可看列表小节)
例子:当用户输入quit停止
prompt = "tell me sth"
prompt += "\nEnter 'quit' to end!"
message = ''
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
cotinue与break
continue:跳过循环中continue后的代码,直接开始下一轮循环
break:退出循环
例子:使用continue与break打印1-10内的奇数
# continue break
num = 0
while True:
num += 1
if num % 2 == 0:
continue
if num>10:
break
print(num)
使用while循环处理列表与字典
例子1:验证用户列表(pop()可看列表一节)
# 列表
unconfirmed_users = ['a', 'b', 'c']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: "+ current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
例子2:删除列表中特定元素(列表中元素可以重复多个)
pets = ['dog', 'cat', 'fish', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
例子3:问卷调查(将姓名与回答作为键值对)
字典:responses 键:name 值:response,输入N停止调查,Y继续
responses = {}
flag = True
while flag:
name = input("what's your name? :")
response = input("which pets do you like? :")
responses[name] = response
repeat = input("continue? Y/N :")
if repeat == 'N':
flag = False
for name, response in responses.items():
print(name+' likes '+response+'.')
函数
函数的定义与传递信息
位置实参:实参关联到函数形参的方式基于实参的顺序
def get_fullname(firstname,lastname):
fullname = firstname+" "+lastname
return fullname.title()
print(get_fullname("w", "k"))
关键字实参:直接在实参中将名称和值关联起来
def describe_pet(pet_type, pet_name):
print("my "+pet_type+"'s name is "+pet_name)
describe_pet(pet_name='aim',pet_type='cat')
默认值:在定义时给形参指定默认值
def describe_pet(pet_type='dog', pet_name='bob'):
print("my "+pet_type+"'s name is "+pet_name)
describe_pet()
返回字典
# 返回字典
def build_person(first_name, last_name, age = 0):
"""返回字典,包含一个人的信息"""
person = {'firstname': first_name,'lastname': last_name}
if age:
person['age'] = age
return person
actor = build_person('jack', 'chen', 50)
print(actor)
结合用户输入,While循环
def get_name(first_name, last_name):
full_name = first_name+ " "+last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' to quit)")
f_name = input("first name:")
if f_name == 'q':
break
l_name = input("last name:")
if l_name == 'q':
break
formatted_name = get_name(f_name, l_name)
print("hello "+ formatted_name+"!")
列表
# 列表
def greet_users(names):
"""向列表每个用户问候"""
for name in names:
print("Hello " + name.title()+"!")
users = ['bob', 'jack', 'mary']
greet_users(users)
函数修改列表
验证用户列表,将验证的用户添加到已验证列表
def verify_user(unconfirmed_users, comfirmed_users):
"""验证用户,将验证用户添加到已验证列表"""
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
def print_users(confirmed_users):
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
unconfirmed_users = ['bob', 'mary', 'jack']
confirmed_users = []
verify_user(unconfirmed_users, confirmed_users)
print_users(confirmed_users)
禁止函数修改列表
用切片表示法[:]创建列表副本,例如在函数中传递用户列表user[],进行操作后原用户列表不变
function(user[:])
传递任意数量实参
def using_languages(*langusges):
print("I'm using langusges:")
for langusge in langusges:
print(langusge)
using_languages('c')
using_languages('c', 'python', 'java')
使用任意数量关键字实参
def build_profile(first, last, **user_info):
profile = {}
profile['firstname'] = first
profile['lastname'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_info = build_profile('Tibert', 'jack', tel = '2323',adress = 'wuhan')
print(user_info)
将函数存储在模块中
先创建模块,模块扩展名为.py文件
例子:利用简单模块,制作pizza
pizza.py
def make_pizza(size, *toppings):
"""概述制作pizza"""
print("\nMaking a "+ str(size) + "-inch pizza with the following toppings: ")
for topping in toppings:
print(topping)
making_pizzas.py
import pizza
pizza.make_pizza(16, 'mushrooms')
pizza.make_pizza(12,'green peppers', 'cheese')
导入特定函数
from module_name import function_0, function_1...function_n
假设上个例子中pizza.py中有多个函数,但只想导入make_pizza
from pizza import make_pizza
解决导入模块报错,但运行正常
可以参考博客:pycharm的使用
使用as给函数指定别名
别名使用起来更加方便:
import tensorflow as tf
导入模块中所有函数:
from module_name import *
函数编写指南
需要注意给形参指定默认值时,等号两边不要空格
调用时也是如此
类
创建类
类中的方法必须含有形参self
class dog():
"""模拟小狗的简单测试"""
def __init__(self, name, age):
"""初始化属性"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗蹲下"""
print(self.name.title()+ " is now sitting.")
def running(self):
"""模拟小狗奔跑"""
print(self.name.title() + " is now runnning.")
创建实例,调用方法
my_dog = Dog('bob', 3)
print("My dog's name is " + my_dog.name.title())
print("My dog's is " + str(my_dog.age)+" years old.")
my_dog.sit()
my_dog.running()
属性指定默认值,修改属性
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_car_info(self):
car_info = str(self.year) + ' ' + self.make + ' ' + self.model
return car_info.title()
def update_odometer_reading(self, mile):
self.odometer_reading += mile
def get_odmeter(self):
"""打印里程信息"""
print("This car has "+ str(self.odometer_reading)+" miles on it.")
my_new_car = Car('Audi', 'a4', 2016)
print(my_new_car.get_car_info())
my_new_car.get_odmeter()
# 直接修改属性
my_new_car.odometer_reading = 20
my_new_car.get_odmeter()
# 通过方法修改属性
my_new_car.update_odometer_reading(30)
my_new_car.get_odmeter()
继承
class ElectricCar(Car):
"""电动汽车"""
def __init__(self, make, model, year):
"""初始化父类"""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_car_info())
my_tesla.update_odometer_reading(10)
my_tesla.get_odmeter()
可以给子类定义自己的属性和方法,而此时父类并不包含它们
可以重写父类的方法,子类调用该方法时,将忽略父类的该方法,只关注在子类中重写的方法
将实例用作属性
完整例子:三个类,电瓶,车,电瓶车,电瓶车继承车,电瓶车将电瓶实例用作属性
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_car_info(self):
car_info = str(self.year) + ' ' + self.make + ' ' + self.model
return car_info.title()
def update_odometer_reading(self, mile):
self.odometer_reading += mile
def get_odmeter(self):
"""打印里程信息"""
print("This car has "+ str(self.odometer_reading)+" miles on it.")
class Battery():
"""模拟电瓶"""
def __init__(self , battery_size = 70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a "+ str(self.battery_size)+"-kwh battery.")
def get_range(self):
"""指出电瓶续航里程"""
if self.battery_size == 70:
range = 240
elif self.battery_size ==85:
range = 270
msg = "This car can go approximately "+ str(range)+ " miles on a full charge."
print(msg)
class ElectricCar(Car):
"""电动汽车"""
def __init__(self, make, model, year):
"""初始化父类"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_car_info())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
导入类(结合上例)
car.py中有上例三个类
my_car.py导入类
导入car.py的Car类
from car import Car
导入car.py多个类
from car import Class1, Class2
导入整个模块
import car
# 使用
my_beetle = car.Car('volkswageb', 'beetle', '2000')
导入car中所有类:
from car import *
也可在一个模块导入另一个模块
Python标准库
模块collection中含一个类OrdereDict,记录键值对的添加顺序
文件
打开读取文件,以及相对路径绝对路径
打开文件,读取文件分别调用方法open(),read()
定义了一个函数:
file_reader.py
# 打开文件,读取内容
def open_read(path):
with open(path) as file_object:
contents = file_object.read()
print(contents)
目录结构如下:
pi_digits.txt 与file_reader.py在同一目录
path = 'pi_digits.txt'
open_read(path)
2.txt在file_reader.py所在目录的子目录
# 相对路径
path = 'txt/2.txt'
open_read(path)
使用1.txt绝对路径
# 文件路径(绝对路径)
path = 'E:\python\PycharmProject\python_study\基础语法\类/1.txt'
open_read(path)
解决读取文件时多读取一行空行
原因:read()到达文件末尾会返回空字符串,显示出来就是空行
方法:使用rstrip()函数:
# 打开文件,读取内容
def open_read(path):
with open(path) as file_object:
contents = file_object.read()
print(contents.rstrip())
逐行读取
方法1:用到for循环
def open_read_byline(path):
with open(path) as file_object:
for line in file_object:
print(line.rstrip())
path = 'txt/3.txt'
open_read_byline(path)
方法二:
将文件各行存储到列表:
先逐行读取到列表lines,函数返回该列表
def open_read_byline(path):
with open(path) as file_object:
lines = file_object.readlines()
return lines
path = 'txt/3.txt'
txt_lines = open_read_byline(path)
for line in txt_lines:
print(line.rstrip())
使用文件中的内容
需要用到上个例子的方法二:
例子:将txt内容存储到变量中(记得删除两边空格)
def open_read_byline(path):
with open(path) as file_object:
lines = file_object.readlines()
return lines
pi_string = ''
path = 'pi_digits.txt'
txt_lines = open_read_byline(path)
for line in txt_lines:
pi_string += line.strip()
print(pi_string)
处理包含一百万位的大型文件
假设pi.digits小数点后有一百万位
代码前面不变,只需最后打印时处理
运用切片:
精确到后50位:
print(pi_string[:52] + '...')
print(len(pi_string))
圆周率后一百万位文件:下载地址
下载源代码文件,第十章,pi_million_digits
写入空文件
记得赋予写权限open(filename, ‘w’)
写入多行记得加换行
filename = 'programming.txt'
with open(filename, 'w') as file_project:
file_project.write("I like programming\n")
file_project.write("I like creating new game\n")
附加内容到文件
open()中参数改为’a’即可
filename = 'programming.txt'
with open(filename, 'a') as file_project:
file_project.write("copy:I like programming\n")
file_project.write("copy:I like creating new game\n")
最终文件中内容:
异常
除数为0异常:try-except
print("Please enter two number,I'll divide them")
print("Enter 'q' to quit!")
while True:
first_num = input("\nFirst number:")
if first_num == 'q':
break
second_num = input("Second number:")
try:
answer = int(first_num)/int(second_num)
except ZeroDivisionError:
print("can't divide by zero!")
else:
print(answer)
文件未找到异常:
file = 'abcd.txt'
try:
with open(file) as file_obj:
contents = file_obj.read()
except FileNotFoundError:
msg = "Sorry! file do not exit!"
print(msg)
分析文本
分别估算多篇文章的单词:split()方法,以空格为分隔符将字符串分拆为多个部分,存储到列表
# 计算一个文件大致包含多少单词
def count_words(filename):
"""计算一个文件大致包含多少单词"""
try:
with open(filename) as file_obj:
contents = file_obj.read()
except FileNotFoundError:
msg = "Sorry! file do not exit!"
print(msg)
else:
words = contents.split()
num_words = len(words)
return num_words
files = ['a.txt', '1.txt', '2.txt']
for file in files:
num_words = count_words(file)
if num_words:
print("The " + file + " has about "+ str(num_words)+" words!")
不希望输出异常信息,将except后的语句改为pass
以JSON格式存储数据
将数字列表存储到number.json(无需自己创建number.json)
import json
num = [1, 2, 3, 4]
filename = "numbers.json"
with open(filename, 'w') as f_obj:
json.dump(num, f_obj)
打开并读取number.json
import json
filename = "numbers.json"
with open(filename) as f_obj:
number = json.load(f_obj)
print(number)
重构
改进代码,划分为一系列完成具体工作的函数
例如:完成1.根据提示输入用户名数据存储
2.对存储的数据进行访问
import json
def get_stored_username():
"""获取存储的用户名"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
username = get_stored_username()
if username:
print("welcome back! "+ username)
else:
username = input("What's your name?")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back!."+ username)
greet_user()
测试代码
python标准库中模块unittest提供了测试工具
待测试:name_function.py
def get_formatted_name(first, middle, last):
"""返回整洁姓名"""
full_name = first + ' ' + middle + ' ' + last
return full_name.title()
测试脚本
self.assertEqual:判断调用函数得到的字符串与目的字符串是否一致
test_name_function.py
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
def test_first_last_name(self):
formatted_name = get_formatted_name('a', 'b', 'c')
self.assertEqual(formatted_name, 'A B C')
unittest.main()
结果:
修改测试代码:
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
def test_first_last_name(self):
formatted_name = get_formatted_name('a', 'b')
self.assertEqual(formatted_name, 'A B')
unittest.main()
测试出错,则要修改函数get_formatted_name()
修改后:name_function.py
def get_formatted_name(first, last, middle=''):
"""返回整洁姓名"""
if middle:
full_name = first + ' ' + middle + ' ' + last
else:
full_name = first + ' ' + last
return full_name.title()
添加测试
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
def test_first_last_name(self):
formatted_name = get_formatted_name('a', 'b')
self.assertEqual(formatted_name, 'A B')
def test_first_middle_last_name(self):
formatted_name = get_formatted_name('a', 'c', 'b')
self.assertEqual(formatted_name, 'A B C')
unittest.main()
处理报错:空测试套件
可以参考博客:pycharm的使用
断言方法
# a == b?
assertEqual(a, b)
# a != b?
assertNotEqual(a, b)
# x == True?
assertTrue(x)
# x == False?
assertFalse(x)
# item在list 中?
assertIn(item, list)
# item不在list 中?
assertNotIn(item, list)
测试类
survey.py
class Survey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_response(self):
print("Result: ")
for response in self.responses:
print("--"+ response)
测试:responses中的元素是否存储到my_survey.responses列表
setUp()方法:只需创建对象一次,并在后面的每个测试方法使用
import unittest
from survey import Survey
class Test_Survey(unittest.TestCase):
def setUp(self):
question = "What language did you first to learn?"
self.my_survey = Survey(question)
# my_survey.responses列表为空
#模拟的回答
self.responses = ['c', 'c++', 'python']
def test_store_one_response(self):
self.my_survey.store_response(self.responses[0])
# 执行完上一行,若存储成功,则my_survey.responses = ['c']
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_response(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()