Python_revision

文章目录

      • 2.2 变量
      • 2.2.1 变量的规则
      • 3.3 列表
        • 3.3.1 添加
        • 3.3.2 删除
        • 3.3.3 排序
        • 3.4.1 遍历
        • 3.4.3 创造数值列表
          • 3.4.3.1 用range() 创造列表
          • 3.4.3.2 简单统计计算
          • 3.4.3.4 列表解析
        • 3.4.4 使用列表一部分
          • 3.4.4.1 切片
      • 3.5 元组
    • 5 if
      • 5.2 if 检查特定值
        • 5.2.1 包含
        • 5.2.2 不包含:
      • 5.3 if 检查多种情况
      • 5.4 确定列表为空
    • 6 字典
      • 6.1 取用
      • 6.2 添加
      • 6.3 修改
      • 6.4 删除
      • 6.5 遍历
        • 6.5.1 遍历键**—**值对
        • 6.5.2 遍历所有keys(默认)
          • 6.5.2.1 无序
          • 6.5.2.2 有序(字母表顺序)
        • 6.5.3 遍历value
      • 6.6 嵌套
        • 6.6.1 字典列表
        • 6.6.2 在字典中存储列表
        • 6.6.3 在字典中存储字典
    • 7 用户输入
    • 7.1 input()
        • 7.1.2 int()
    • 8 while
      • 8.1 使用break推出循环
      • 8.2 使用continue 回到开头
    • 9 函数
      • 9.1 关键字实参
        • 9.1.2 默认值
      • 9.2 传递列表
        • 9.2.1 传递副本
      • 9.3 传递任意数量实参 *toppings
        • 9.3.2 结合使用位置实参和任意数量实参
      • 9.4 使用任意数量的关键字实参
      • 9.5 将函数存储在模块中
    • 10 类
      • 10.1 创造和使用类
        • 10.1.2 修改属性的值
      • 10.2 继承
        • 10.2.1 重写父类方法
        • 10.2.2 将实例用作属性
      • 10.3 导入类
    • 11 读取文件
      • 11.1 逐行读取
      • 11.2 创建一个包含文件各行内容的列表
    • 12 写入文件
      • 12.1 写入空文件
    • 13 异常
      • 13.1 使用异常避免崩溃
      • 13.2 不处理异常
    • 14 分析文本
      • 14.1 spit()
    • 15 存储数据
      • 15.1 使用json.dump() 和 json.load()
    • 16 测试代码
      • 16.1 测试方法
      • 16.2 测试类
      • 16.3 setUp() 方法

2.2 变量

2.2.1 变量的规则

  • 只能有数字,字母和下划线( _ ),数字不能开头
  • 不能有空格

3.3 列表

bicyle=['cannondale','trek']
bicyle[0]
#只返回元素,不包括方括号和引号
bicyle[-1]
#-1返回最后一个,-2返回倒数第二个
3.3.1 添加
bicyle.append()
#添加至末尾
bicyle.insert(0,'ducati')
#将元素添加至索引0 的位置
3.3.2 删除
del bicyle[0]
#删除,任意位置的
bicyle.pop()
#删除末尾元素,并且返回该元素
bicyle.pop(1)
#删除指定位置元素,并且返回该元素
bicyle.remove('trek')
#根据值删除元素,并且返回该元素(只删除第一个指定的值,如果一个值重复出现很多次,用循环判断是否删除完)
3.3.3 排序
bicyle.sort()
#安字母表排序,顺序是永久的
message = ['a', 'b', 'v', 'A', 'B', 'G', '1', '2', '5', '36', '-3', '-21']
message.sort()
print(message)
# result: ['-21', '-3', '1', '2', '36', '5', 'A', 'B', 'G', 'a', 'b', 'v']
message.sort(reverse=true)
#按与上面方法相反排列
sorted(bicyle)
#临时排序打印
bicyle.reverse()
#将列表倒着打印
len(bicyle)
#返回bicycle的长度
3.4.1 遍历
for bike in bicyle:
  print(bike)
3.4.3 创造数值列表
for number in range(1,5):
  print(number)
#打印1~4(左含右不含)
3.4.3.1 用range() 创造列表
number = list(range(1,6))
# [1, 2, 3, 4, 5]
number2 = list(range(2,11,2))
#指定步长   [2, 4, 6, 8, 10]
3.4.3.2 简单统计计算
min(number)
max(number)
sum(number)
3.4.3.4 列表解析
squares = [value**2 for value in range(1,11)]
3.4.4 使用列表一部分
3.4.4.1 切片
number[0:3]
#返回一个列表,3个元素,左含右不含
number[:3]
#从开头到索引为3
number[3:]
#从索引为3到结尾
number[-3:]
#返回最后3个

3.5 元组

元组不可以修改,列表可以修改

dimension = (200,50)

5 if

5.2 if 检查特定值

5.2.1 包含
if bike in bicyle :
  
5.2.2 不包含:
if bike not in bicyle:
  

5.3 if 检查多种情况

if age < 4:
  print()
elif age < 18 :
  print()
elif age < 38 :
  print()
else : #else 可以省略
  print()

5.4 确定列表为空

bicyle = []
if bicyle:
  print()
 #如果不是空,true

6 字典

alien_0 ={'color':'green','points':5}

6.1 取用

print(alien_0['color'])
#通过key 找到value

6.2 添加

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

6.3 修改

alien_0['color']='red'

6.4 删除

del alien_0['name']

6.5 遍历

6.5.1 遍历键**—**值对

可声明任意两个变量用于存储

for k , v in alien_0.items()
# items() 返回键-值对列表。
#返回的顺序可能与存储的顺序不同 ,键—值对的存储顺序,而 只跟踪键和值之间的关联关系
6.5.2 遍历所有keys(默认)
6.5.2.1 无序
for k in alien_0.keys():
#顺序可能不同 keys()方法可以不写,是默认遍历key的
#key()返回一个列表,可用于确认某个键是否在keys中
6.5.2.2 有序(字母表顺序)
for k in sorted( alien_0.keys() ):
6.5.3 遍历value
for v in alien_0.values():
for v in set( alien_0.values() ):
  #剔除重复的value,set集合不能重复

6.6 嵌套

将字典存在列表中,或将列表做为值存在字典中

6.6.1 字典列表

将字典存在列表中

alien_0 = {'color': 'green', 'points': 5} 
alien_1 = {'color': 'yellow', 'points': 10} 
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]
6.6.2 在字典中存储列表

列表做为值存在字典中

pizza = {
		'crust': 'thick',
		'toppings': ['mushrooms', 'extra cheese'], 
}
6.6.3 在字典中存储字典
users = {
  		'aeinstein': {
					'first': 'albert', 
        	'last': 'einstein', 
        	'location': 'princeton', 
      							},
			'mcurie': {
					'first': 'marie',
        	'last': 'curie', 
        	'location': 'paris',
      					},
}

7 用户输入

7.1 input()

message = input("Enter your name : ")
# 里面文字为提示内容, message 值为键盘输入值
#有时提示超过了一行,则:
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
7.1.2 int()

输入的所有为字符串

int("21")

8 while

8.1 使用break推出循环

while True:
  if city == 'haha':
    break
  else:
    print()

8.2 使用continue 回到开头

current_number = 0
while current_number < 10:
		current_number += 1
		if current_number % 2 == 0:
				continue 
    print(current_number)
 # 打印奇数

9 函数

9.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(animal_type='hamster',pet_name='harry')
#等号两边不要有空号
#防止传递参数时混淆
9.1.2 默认值
def describe_pet(animal_type, pet_name='dog'):
  #等号两边不要有空号
  print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  
describe_pet(pet_name='harry')
describe_pet(animal_type='hamster',pet_name='harry')
#默认是 dog,也可以指定

9.2 传递列表

def greet_users(names):
  for name in names:
			msg = "Hello, " + name.title() + "!" 					print(msg)
      
usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)
9.2.1 传递副本
function_name(list_name[:])

9.3 传递任意数量实参 *toppings

通过形参 *toppings 来传递所有实参

def make_pizza(*toppings):
9.3.2 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
  
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

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

传递键-值对参数

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)

9.5 将函数存储在模块中

将函数保存在name.py 的文件中,使用时导包

def make_pizza(size ,*toppings):
  
#将其保存在pizza.py z中
#导入整个模块
import pizza
pizza.make_pizza(16,'','','')
#导入特定函数
from pizza import make_pizza
make_pizza(16,'','','')

#函数指定别名
from pizza import make_pizza as mp
mp(16,'','','')

#模块指定别名
import pizza as p
p.make_pizza(16,'','','')

10 类

10.1 创造和使用类

#根据约定,在python中,首字母大写的指类
class Dog():
  
  #每次Dog类创造实例时,都会自动运行该方法
  #形参self
  #每个属性都必须要有初始值,哪怕是0或空字符串,如果设定了默认值,则无需形参。
  def __init__(self,name,age):
    self.name = name
    self.age = age
    self.type = dog
  # 以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量。self.name = name 获取存储在形参name中的值,并将其存储到变量 name 中,然后该变量被关联到当前创建的实例。
  
    
  def sit(self):
    print()
    
  def roll_over(self):
    print()

为什么在方法定义中包含形参self?

因为Python调用 这个__init__() 方法来创建实例时,将自动传入实参self 。每个与类相关联的方法调用都自动传递实参self ,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。

以self 为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量,而这个变量称为属性

#创键实例
#主动调用__init__()方法,使用我们提供的值来设置属性,自动返回表示这条小狗的实例
my_dog = Dog('willie',6)
#访问属性
print(my_dog.name)
print(my_dog.age)
#使用方法
my_dog.sit()
10.1.2 修改属性的值
  1. 直接修改

    my_dog.name = 'JinZY'
    
  2. 通过方法修改属性的值

    def update_name(self,name):
      self.name = name
    
  3. 通过方法对属性的值进行递增

    def add_name (self,oname):
      self.name += oname
    

10.2 继承

#父类必须包含在当前文件中,且位于子类前面
class Dog():
  def __init__(self,name,age):
    self.name = name
    self.age = age
    self.type = dog
    
  def sit(self):
    print()
    
  def roll_over(self):
    print()
    
class otherDog(Dog):
  def __init__(self,name,age):
     #调用父类的方法
    super().__init__(self,name,age)
    #定义自己的属性
    self.weight = 70
10.2.1 重写父类方法
10.2.2 将实例用作属性
class Dog():
  def __init__(self,name,age):
    self.name = name
    self.age = age
    self.type = dog
    
  def sit(self):
    print()
    
  def roll_over(self):
    print()

#可以描述这个类的细节,而不影响OtherDog
class weight():
  def __init__(self,weight):
    self.weight = weight
    
  def describe_weight(self):
    print()
    
class OtherDog(Dog):
  def __init__(self,name,age):
     #调用父类的方法
    super().__init__(self,name,age)
    #定义自己的属性
    self.weight = weight()
    
my_dog = OtherDog('mike',9)
my_dog.describ_weight()
my_dog.sit()

10.3 导入类

from ** import ****

可以在一个模块中导入另一个模块

11 读取文件

with open("filename.txt") as file_object:
  contents = file_object.read()
  print(contens.rstrip())
  #rstrip()消除空白行

11.1 逐行读取

with open("filename.txt") as file_object:
  for line in file_object;
  	

11.2 创建一个包含文件各行内容的列表

#用with 关键字时,open()返回的对象,只在with代码块内可用。
with open("filenam.txt") as file:
  #readlines()返回一个列表
  lines = file.readlines()
for line in lines:
  print()

12 写入文件

12.1 写入空文件

with open(filename,'w') as file_object:
  file_object.write("hahahah")
#open( ,"") 有多个参数 : 读取模式(r),写入模式(w),附加模式(a),读取和写入模式(‘r+’)
#open() 的对象如果存在,则清空文件再写入,不存在就创建新的文件
#只能写入字符串,用str()装成字符串
#附加模式(‘a’) : 将写入的行添加到文末,而不会覆盖原本内容

13 异常

异常是使用try-except代码块处理的,

try:
  print(5/0)
#tell python what to do rather than stop the program
except ZeroDivisonError:
  print("can't be 0")
print("ahahhah")
# result:
#					Can't be 0
#					hahahahha

13.1 使用异常避免崩溃

使用else:

while True:
  first_name = input("Enter the first name")
  if first_name == 'q':
    break
  second_name = input("Second name")
  #可能发生异常的代码块放在try中
  try:
    ansewer = int(first_name)/int(second_name)
  #有错误应该怎做
  except ZeroDivisionError:
    print("you can't dived by 0")
  #如果没有报错改怎么样
  else:
    print(answer)
                    

13.2 不处理异常

try:
 
except ******Error:
  pass
else:
  

14 分析文本

14.1 spit()

:以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。

try:
    with open("test.txt") as t:
        lines = t.readlines()
except FileNotFoundError:
    print("The file is not found")
word=[]
for line in lines:
    word +=line.split()
print(len(word))

15 存储数据

15.1 使用json.dump() 和 json.load()

模块json 让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。

import json

number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
with open("Tryjson.json", 'w') as T:
    json.dump(number, T)
 
#Tryjson.json 内的内容:
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
with open("Tryjson.json") as T:
    number = json.load(T)
    print(number)
 #result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

16 测试代码

16.1 测试方法

模块unittest 提供了代码测试工具,

import unittest
#导入被测试的方法
from name_function import get_formatted_name
#创造类用于包含一系列针对某一方法的单元测试,要继承unittest.TestCase类
class NameTestCase(unittest.TestCase):
  #在运行时,所有以test打头的方法都自动运行
  def test_firstname(self):
    #判断得到的与期望的是否相同
		self.assertEqual("The result from method" ,"The except" )
#让python运行这个文件中的测试
unittest,main()

16.2 测试类

与测试方法的方法相同

import unittest
#导入被测试的类
from survey import AnonymousSurvey
class TestAnonmyousSuivey(unittest.Testcase):
  def test_store_single_response(self):
    
    
unittest.main()
方法 用途
assertEqual(a,b) whether a==b
assertNotEqual(a,b) whether a!=b
assertTrue(x) whether x is True
assertFalse(x) whether x is False
assertIn(item,list) whether item in list
assertNotIn(item,list) whether item not in list

16.3 setUp() 方法

unittest.TestCase包中有setUp()方法,如果在测试类中先重写setUP(),则先运行setUP()方法,再运行以test开头的方法。

通过setUP()来构造对象,和接收得到的返回值

你可能感兴趣的:(python)