Python学习之路

360 阅读9分钟

一、列表操作函数

1.在列表末尾添加元素

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')

2.在列表中插入元素

motorcycles.insert(0, 'ducati') #0代表插入数组的位置

3.从列表删除元素

del motorcycles[0] #0同上

4.从列表中弹出元素

(1) 弹出列表最后一个元素
popped_motorcycle = motorcycles.pop()
(2) 弹出任意位置的元素
popped_motorcycle = motorcycles.pop(0)

5.根据值删除元素

motorcycles.remove('ducati')

6.对元素进行排序

(1) 按照首字母排序
motorcycles.sort() #列表被永久改变
a=sorted(motorcycles) #列表被临时改变
(2) 反转元素顺序
motorcycles.reverse()

7.确定列表长度

len(motorcycles)

二、列表操作常用语句

1.遍历列表

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)

2.创建数值列表

(1) 等差数列组成数值列表
even_numbers = list(range(2,11,2)) #从2-11步长为2的等差序列
(2) 其他函数组成的数值型列表
f = []
for value in range(1,11)
    f.append(value**2) #构建平方型数组
(3) 列表解析法一步到位
squares = [value**2 for value in range(1,11)]

3.数值列表统计计算

min(squares)
max(squares)
sum(squares)

4.使用列表的一部分

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) #打印列表序号为0、1、2的元素
print(player[1:4]) #打印列表序号为1、2、3的元素
print(player[:4]) #打印列表序号为0、1、2、3的元素
print(player[2:]) #从列表序号为2的元素开始打印至末尾
print(player[-3:]) #从列表序号为-3的元素打印至末尾
#遍历切片
for player in players[:3]:
    print(player)
#复制列表
football_player = players[:]

5.不可变列表———元组

dimensions = (200,50) #定义元组
for dimension in dimensions 
    print(dimension) #遍历元组

三、if语句+相关条件表达

1.if用法+条件表达

arr = [value for value in range(1,11)]
if a==b: #检测是否相等
elif a!=b: #检测是否不相等
elif a in arr: #检测a是否在arr中
elif a not in arr: #检测a是否不在arr中
elif (a==0) and (b==0): #与条件检测
elif (a==0) or (b==0): #或条件检测
else arr: #确定列表不是空的

四、字典

1.定义字典

alien_0 = {
    'color': 'green',
    'points': 5,
    } #键-值对
print(alien_0['color']) #根据键打印相关值

2.添加键-对值

alien_0['x_position'] = 0 #添加新键x_position
alien_0['y_position'] = 25 #添加新键y_position

3.修改/删除键-对值

aline_0['color'] = yellow #修改颜色为yellow
del alien_0['point'] #删除point键

4.遍历字典

for key,value in alien_0.items(): #用key和value存储遍历出的键、值
for key in alien_0.keys(): #遍历键
for key in sorted(alien_0.keys): #按照顺序遍历键
for key in alien_0: #同遍历键
for value in alien_0.values(): #遍历值

5.字典嵌套

(1) 字典嵌套在列表中
aliens = []
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)
(2) 列表嵌套在字典中
favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    }
for name,languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:"
    for language in languages
        print("\t"+language.title())
(3) 字典嵌套在字典中
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },
    }
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())  

###五、用户输入+while循环

1.input函数

name = input("Please enter your name: ") #单个字符输入
print("Hello, " + name + "!")
month,day = input("请输入日期,用'5.12'的形式\n").split('.')) #多个字符,输入用句点分割
month,day = map(int,input("请输入日期,用'5.12'的形式\n").split('.')) #多个整数输入,用句点分割

2.while循环

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

3.在while循环中使用break

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
    city = input(prompt)
    if city == 'quit':
    break
    else:
    print("I'd love to go to " + city.title() + "!")

4.用while进行列表操作

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

六、函数

1.函数格式

def greet_user(username):
"""显示简单的问候语"""
    print("Hello, " + username.title() + "!")
greet_user('jesse')

2.传递实参

(1) 位置实参
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('hamster', 'harry')
(2) 关键字实参
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')
(3)默认值
def describe_pet(pet_name, animal_type='dog'): #注意形参指定默认值'='两边不要有空格
"""显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')

3.返回值

(1) 返回简单值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
(2) 返回字典
def build_person(first_name, last_name):
"""返回一个字典, 其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    return person
musician = build_person('jimi', 'hendrix')
print(musician)

4.传递列表

(1) 传递格式,此时列表可在函数中更改
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
(2) 传递列表副本
function_name(list_name[:])

5.传递位置实参+任意数量的实参

def make_pizza(size, *toppings): #剩下的参数都存在toppings元组中
"""概述要制作的比萨"""
    print("\nMaking a " + str(size) +
        "-inch pizza with the following toppings:")
    for topping in toppings:
    print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

6.传递任意数量的关键字实参

def build_profile(first, last, **user_info): #键值对模式
"""创建一个字典, 其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',
                            location='princeton',
                            field='physics')
print(user_profile)

7.将函数存储在模块中

(1) 导入整个模块
#pizza.py
def make_pizza(size, *toppings):
    for topping in toppings:
        print("-" + topping)
#makeing_pizaas.py
import pizza
    pizaa.make_pizza(16,'pepperoni') #调用函数方式module_name.function_name()
(2) 导入特定的函数
from pizaa import make_pizza

make_pizza(16,'pepperoni') #调用函数无需句点

(3) 使用as给函数指定别名

from pizza import make_pizza as mp

mp(16,'pepperoni') #直接利用函数别名

(4) 使用as给模块别名

import pizza as p

p.make_pizza(16,'pepperoni') #利用模块别名

(5) 导入模块中的所有函数

from pizza import *

make_pizza(16,'pepperoni')

七、类

1.创建类

class Dog():
"""一次模拟小狗的简单尝试"""
    def __init__(self, name, age): #初始化类的函数
    """初始化属性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!")

2.创建实例

my_dog = Dog('willie', 6) 
your_dog = Dog('lucy', 3)
my_dog.name #访问属性
my_dog.sit() #调用方法

3.修改实例属性

class Car():
    """一次模拟汽车的简单尝试"""
    def __init__(self, make, model, year): 
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer = 0
    def get_descriptive_name(self): 
        """返回整洁的描述性信息"""
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        """打印一条指出汽车里程的消息"""
        print("This car has " + str(self.odometer) + " miles on it.")
    def update_odometer(self, mileage): 
        """将里程表读数设置为指定的值"""
        self.odometer = mileage
    def increment_odometer(self, miles):
        """将里程表读数增加指定的量"""
        self.odometer += miles

my_new_car = Car('audi', 'a4', 2016) #创建实例
my_new_car.odometer = 23 #直接修改属性
my_new_car.read_odometer(23) #调用函数修改
my_new_car.increment_odometer(100) #调用函数修改

4.继承

class ElectricCar(Car):
    """ 电动汽车的独特之处 """
    def __init__(self,make,model,year):
        """初始化父类的属性"""
        super().__init__(make,modle,year) #调用super函数将父类和子类结合
        self.battery_size = 70 #子类独有属性
    def describe_battery(self):
        print(str(self.battery_size) #子类独有函数
#继承了父类的一切
my_tesla = ElectricCar('tesla','model's',2016)
print(my_tesla.get_descriptive_name())

5.重写父类的方法

#假设父类中存在fill_gas_tank()
def ElectricCar(Car):
    --snip--
    def fill_gas_tank(): #重写成功
        """电动汽车没有油箱"""
        print("This car doesn't need a gas tank!")

6.将实例用作属性

class Car():
    --snip--
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.")
            
class ElectricCar(Car):
    """电动汽车的独特之处"""
    def __init__(self, make, model, year):
    """     
    初始化父类的属性, 再初始化电动汽车特有的属性
    """
        super().__init__(make, model, year)
        self.battery = Battery()
        
my_tesla = Electrical('tesla','model_s',2016)
my_tesla.battery.describe_battery() #调用类中类

7.导入类

import car #导入整个模块 car.Car
from car import * #导入所有类
from car import Car,ElectricCar #导入指定类

八、文件与异常

1.读取整个文件

(1) 多种读取方式
with open ('<file-name>') as file_object: #在当前执行文件所在目录查找文件
    contents = file_object.read() #读取的内容以字符变量存储再contents中
    print(contents)
with open('<subfolder/<file-name>') as file_object: #在当前文件目录的子文件夹查找文件
with open ('<file_path>') as file_object: #到指定路径查找文件
    for line in file_object: #逐行读取文件内容
    print(line)
    print(line.rstrip()): #删除多余的空白行
    lines = file_object.readlines() #将各行存储在"列表"中
(2)使用文件内容
filename = '<file-name>'
with open(filename) as file_object:
    lines = file_object.readlines() #列表

pi_string = ''
for line in lines:
    pi_string += line.rstrip()

2.写入空文件

filename = '<file-name>'
with open(filename,'w') as file_object: #以写入模式('w')打开文件,如果写入的文件不存在,函数open()将自动创建,如果写入的文件存在,则清空该文件并返回。
    file_object.write("I love programming.\n")
    file_object.write("I love creating games.\n")
with open(fileoname,'a') as file_object: #将写入的内容附加到文件末尾
    file_object.write("I love creating apps.\n")

4.异常

(1)处理ZeroDivisionError异常
try: #try-except代码块,避免出现tracback
    answer = print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!") 
else:
    print(answer)
(2)处理FileNotFoundError异常
filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)

5.分割文本

filename = 'alice.txt'
try:
    with open(filename) as f_obj:
    contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
    #pass 失败时一声不吭
else:
# 计算文件大致包含多少个单词
words = contents.split() #words为列表
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")

6.存储数据

(1) 将列表数据写入json文件中保存
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj) #dump(list,file_obj)
(2) 从json文件中导入数据
import json
filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)

九、测试代码

1.单元测试

#测试代码 name_function.py
def get_formatted_name(first,last):
    full_name = first + " " + last
    return full_name.title()

#测试方法 tese_name_function.py
import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase): #继承unittest中TestCase类
    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'Janis Joplin') #判断是否一致并给出断言
    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')    
unittest.main()

2.测试类(所有test带头的都会被执行)

(1)断言类型整理
assertEqual(a,b)        #判断是否相等
assertNotEqual(a,b)     #判断是否不等
assertTure(x)           #判断是否为Ture
assertFalse(x)          #判断是否为False
assertIn(item,list)     #判断item是否在list中
assertNotIn(item,list)  #判断item是否不在list中
(2)实例测试类
#survey.py
class AnonymousSurvey():
	"""收集匿名调查问卷的答案"""
	def __init__(self, question):
		"""存储一个问题, 并为存储答案做准备"""
		self.question = question
		self.responses = []
		
	def show_question(self):
		"""显示调查问卷"""
		print(question)
		
	def store_response(self, new_response):
		"""存储单份调查答卷"""
		self.responses.append(new_response)
		
	def show_results(self):
		"""显示收集到的所有答卷"""
		print("Survey results:")
		for response in responses:
			print('- ' + response)
			
#test_survey.py 
import unittest
from survey import AnonymousSurvey

class TestAnonmyousSurvey(unittest.TestCase):
	"""针对AnonymousSurvey类的测试"""
	def test_store_single_response(self):
		"""测试单个答案会被妥善地存储"""
		question = "What language did you first learn to speak?"
		my_survey = AnonymousSurvey(question)
		my_survey.store_response('English')
		self.assertIn('English', my_survey.responses)
		
	def test_store_three_responses(self):
		"""测试三个答案会被妥善地存储"""
		question = "What language did you first learn to speak?"
		my_survey = AnonymousSurvey(question)
		responses = ['English', 'Spanish', 'Mandarin']
		for response in responses:
			my_survey.store_response(response)
		for response in responses:
			self.assertIn(response, my_survey.responses)
					
unittest.main()
(3)setUp()方法测试类
import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
	"""针对AnonymousSurvey类的测试"""
	def setUp(self):
		"""
		创建一个调查对象和一组答案, 供使用的测试方法使用
		"""
		question = "What language did you first learn to speak?"
		self.my_survey = AnonymousSurvey(question)
		self.responses = ['English', 'Spanish', 'Mandarin']
			
	def test_store_single_response(self):
			"""测试单个答案会被妥善地存储"""
			self.my_survey.store_response(self.responses[0])
			self.assertIn(self.responses[0], self.my_survey.responses)
				
	def test_store_three_responses(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()

十、其他

(1)if __name__ == '__main__':

print('this is one')        #被import和直接执行都会调用
if __name__ == '__main__'   #__name__为python内置变量,当直接执行时条件成立
    print('this is two')    #被import时不会都被调用

(2)修改pip源

pip config set global.index-url https://mirrors.ustc.edu.cn/pypi/web/simple