Python基础

作者: TomyZhang | 来源:发表于2020-07-09 19:17 被阅读0次

一、搭建编程环境

在Windows系统中搭建Python编程环境

二、变量和简单数据类型

1.变量

变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头。

message = "Hello Python"

print(message)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(message)

输出:(result.txt)
Hello Python

2.字符串

字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。

message1 = 'This is a string A'
message2 = "This is a string B"
message3 = "This is a string 'C'"
message4 = 'This is a string "D"'

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(message1)
    file_object.write("\n")
    file_object.write(message2)
    file_object.write("\n")
    file_object.write(message3)
    file_object.write("\n")
    file_object.write(message4)

输出:(result.txt)
This is a string A
This is a string B
This is a string 'C'
This is a string "D"

使用方法修改字符串的大小写:

message = "This is a string"

filename = "result.txt"
with open(filename, 'w') as file_object:
    file_object.write(message.title())
    file_object.write("\n")
    file_object.write(message.upper())
    file_object.write("\n")
    file_object.write(message.lower())

输出:(result.txt)
This Is A String
THIS IS A STRING
this is a string

合并(拼接)字符串:

first_name = "tomy"
last_name = "zhang"
full_name= first_name + " " + last_name;

filename = "result.txt"
with open(filename, 'w') as file_object:
    file_object.write(full_name.title())

输出:(result.txt)
Tomy Zhang

使用制表符或换行符来添加空白:

message = "hello\nPython\tJava\tC++"

filename = "result.txt"
with open(filename, 'w') as file_object:
    file_object.write(message)

输出:(result.txt)
hello
Python  Java    C++

删除空白:

message = " hello "

filename = "result.txt"
with open(filename, 'w') as file_object:
    file_object.write(message.rstrip())
    file_object.write("\n")
    file_object.write(message.lstrip())
    file_object.write("\n") 
    file_object.write(message.strip())
    
输出:(result.txt)
 hello
hello 
hello

3.数字

整数:

value1 = 2 + 3
value2 = 2 * 3
value3 = 2 ** 3
value4 = (2 + 3) * 4

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(value1))
    file_object.write("\n")
    file_object.write(str(value2))
    file_object.write("\n")
    file_object.write(str(value3))
    file_object.write("\n")
    file_object.write(str(value4))

输出:(result.txt)
5
6
8
20

浮点数:

value1 = 0.1 + 0.1
value2 = 0.2 + 0.1
value3 = 2 * 0.1
value4 = 3* 0.1

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(value1))
    file_object.write("\n")
    file_object.write(str(value2))
    file_object.write("\n")
    file_object.write(str(value3))
    file_object.write("\n")
    file_object.write(str(value4))

输出:(result.txt)
0.2
0.30000000000000004
0.2
0.30000000000000004

使用函数str()避免类型错误:

value = 30
message = "Happy " + str(value) + "rd Birthday!"

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(message)

输出:(result.txt)
Happy 30rd Birthday!

4.注释

# This is a comment
message = "Hello Python"

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(message)
    
输出:(result.txt)
Hello Python

三、列表

列表由一系列按特定顺序排列的元素组成。

1.访问元素列表

students = ['StuA', 'StuB', 'StuC']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(students[0])
    file_object.write('\n') 
    file_object.write(students[1])
    file_object.write('\n') 
    file_object.write(students[-1])
    file_object.write('\n') 
    file_object.write(students[-2])

输出:(result.txt)
StuA
StuB
StuC
StuB

2.修改、添加和删除元素

修改列表元素:

students = ['StuA', 'StuB', 'StuC']
students[0] = 'StuAAA'

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt)
StuAAA StuB StuC 

在列表中添加元素:

students = ['StuA', 'StuB', 'StuC']
students.append('StuD')
students.insert(0, 'StuP')

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt)
StuP StuA StuB StuC StuD 

使用del语句删除元素:

students = ['StuA', 'StuB', 'StuC', 'StuD']
del students[0]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt)
StuB StuC StuD 

使用方法pop()删除元素:

students = ['StuA', 'StuB', 'StuC', 'StuD']
popped_student1 = students.pop()
popped_student2 = students.pop(0)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
    file_object.write('\n')
    file_object.write('students.pop(): ' + popped_student1)
    file_object.write('\n')
    file_object.write('studengs.pop(0): ' + popped_student2)
    
输出:(result.txt)
StuB StuC 
students.pop(): StuD
studengs.pop(0): StuA

根据值删除元素:

students = ['StuA', 'StuB', 'StuC', 'StuD']
students.remove('StuB')

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt)
StuA StuC StuD 

3.组织列表

使用方法sort()对列表进行永久性排序:

students = ['StuD', 'StuB', 'StuC', 'StuA']
students.sort()

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt)
StuA StuB StuC StuD 
students = ['StuD', 'StuB', 'StuC', 'StuA']
students.sort(reverse=True)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt)     
StuD StuC StuB StuA 

使用函数sorted()对列表进行临时排序:

students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = sorted(students)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
    file_object.write('\n')
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt)     
StuD StuB StuC StuA 
StuA StuB StuC StuD 
students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = sorted(students, reverse=True)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
    file_object.write('\n')
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt)     
StuD StuB StuC StuA 
StuD StuC StuB StuA 

倒着打印列表:

students = ['StuD', 'StuB', 'StuC', 'StuA']
students.reverse()

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt)     
StuA StuC StuB StuD 

确定列表的长度:

students = ['StuD', 'StuB', 'StuC', 'StuA']
length = len(students)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
    file_object.write('\n')
    file_object.write(str(length))

输出:(result.txt)     
StuD StuB StuC StuA 
4

四、操作列表

1.遍历整个列表

students = ['StuD', 'StuB', 'StuC', 'StuA']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt)     
StuD StuB StuC StuA 

2.创建数字列表

使用函数range():

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for value in range(1, 5):
        file_object.write(str(value))
        file_object.write('\n')

输出:(result.txt)     
1
2
3
4

使用range()创建数字列表:

numbers = list(range(1, 6))

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for value in numbers:
        file_object.write(str(value))
        file_object.write('\n')

输出:(result.txt) 
1
2
3
4
5

对数字列表执行简单的统计计算:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(min(numbers)))
    file_object.write('\n')
    file_object.write(str(max(numbers)))
    file_object.write('\n')
    file_object.write(str(sum(numbers)))

输出:(result.txt) 
1
9
45

列表解析:

numbers = [value**2 for value in range(1, 11)]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for number in numbers:
        file_object.write(str(number))
        file_object.write('\n')

输出:(result.txt) 
1
4
9
16
25
36
49
64
81
100

3.使用列表的一部分

切片:

students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = students[0:2]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt) 
StuD StuB 
students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = students[:2]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt) 
StuD StuB 
students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = students[2:]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt) 
StuC StuA 
students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = students[-3:]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt) 
StuB StuC StuA 

遍历切片:

students = ['StuD', 'StuB', 'StuC', 'StuA']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students[-3:]:
        file_object.write(student)
        file_object.write(' ')
        
输出:(result.txt) 
StuB StuC StuA 

复制列表:

students = ['StuD', 'StuB', 'StuC', 'StuA']
new_students = students[:]
new_students[0] = 'StuP'

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student)
        file_object.write(' ')
    file_object.write('\n')
    for student in new_students:
        file_object.write(student)
        file_object.write(' ')

输出:(result.txt) 
StuD StuB StuC StuA 
StuP StuB StuC StuA 

4.元组

定义元组:不可变的列表被称为元组。元组看起来犹如列表,但使用圆括号而不是方括号来标识。

dimensions = (200, 50)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(dimensions[0]))
    file_object.write(' ')
    file_object.write(str(dimensions[1]))
    
输出:(result.txt) 
200 50

遍历元组中的所有值:

dimensions = (200, 50)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for dimension in dimensions:
        file_object.write(str(dimension))
        file_object.write(' ')

输出:(result.txt) 
200 50

修改元组变量:虽然不能修改元组的元素,但可以给存储元组的变量赋值。

dimensions = (200, 50)
dimensions = (400, 100)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for dimension in dimensions:
        file_object.write(str(dimension))
        file_object.write(' ')

输出:(result.txt) 
400 100 

五、if语句

检查是否相等:

student = 'StuA'

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if(student == 'StuA'):
        file_object.write('You are right')
    else:
        file_object.write('You are wrong')

输出:(result.txt) 
You are right

比较数字:

age = 21

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if(age >=10 and age <20):
        file_object.write('age 10+')
    else:
        file_object.write('age not 10+')

输出:(result.txt) 
age not 10+
age = 21

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if(age < 10 or age >= 20):
        file_object.write('age not 10+')
    else:
        file_object.write('age 10+')

输出:(result.txt) 
age not 10+

检查特定值是否包含在列表中:

students = ['StuD', 'StuB', 'StuC', 'StuA']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if 'StuG' in students:
        file_object.write('in list')
    else:
        file_object.write('not in list')    

输出:(result.txt) 
not in list

检查特定值是否不包含在列表中:

students = ['StuD', 'StuB', 'StuC', 'StuA']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if 'StuG' not in students:
        file_object.write('not in list')
    else:
        file_object.write('in list')    

输出:(result.txt) 
not in list

布尔表达式:

state = True

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if state:
        file_object.write(str(True))    
    else: 
        file_object.write(str(False))   

输出:(result.txt) 
True

if-elif-else结构:

age = 21

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if age < 10:
        file_object.write('age < 10')   
    elif age < 20: 
        file_object.write('age >= 10 and age < 20') 
    else:
        file_object.write('age >= 20')  

输出:(result.txt) 
age >= 20

确定列表不是空的:

students = []

filename = 'result.txt'
with open(filename, 'w') as file_object:
    if students:
        file_object.write('list not empty') 
    else:
        file_object.write('list empty') 

输出:(result.txt) 
list empty

六、字典

1.使用字典

访问字典中的值:字典是一系列键-值对。

student = {'name': 'Python', 'age': 10}

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(student['name'])
    file_object.write(' ')
    file_object.write(str(student['age']))

输出:(result.txt) 
Python 10

添加键-值对:

student = {}
student['city'] = 'GuangZhou'
student['dream'] = 'Artist'

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(student['city']))
    file_object.write(' ')  
    file_object.write(str(student['dream']))
    
输出:(result.txt) 
GuangZhou Artist

修改字典中的值:

student = {'name': 'Python', 'age': 10}
student['age'] = 21

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(student['name']))
    file_object.write(' ')  
    file_object.write(str(student['age']))

输出:(result.txt) 
Python 21

删除键-值对:

student = {'name': 'Python', 'age': 10}
del student['age']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(student['name']))

输出:(result.txt) 
Python

由类似对象组成的字典:

student = {
    'StuA': 'Python',
    'StuB': 'Java',
    'StuC': 'C++',
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(student['StuB'])

输出:(result.txt) 
Java

2.遍历字典

遍历所有的键-值对:

student = {
    'StuA': 'Python',
    'StuB': 'Java',
    'StuC': 'C++',
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for key, value in student.items():
        file_object.write(key + ' ' + value)
        file_object.write('\n')

输出:(result.txt) 
StuA Python
StuB Java
StuC C++

遍历字典中的所有键:

student = {
    'StuA': 'Python',
    'StuB': 'Java',
    'StuC': 'C++',
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for key in student.keys():
        file_object.write(key)
        file_object.write('\n')

输出:(result.txt) 
StuA
StuB
StuC

student = {
    'StuA': 'Python',
    'StuB': 'Java',
    'StuC': 'C++',
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for key in student:
        file_object.write(key)
        file_object.write('\n')

输出:(result.txt) 
StuA
StuB
StuC

遍历字典中的所有值:

student = {
    'StuA': 'Python',
    'StuB': 'Java',
    'StuC': 'C++',
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for value in student.values():
        file_object.write(value)
        file_object.write('\n')

输出:(result.txt) 
Python
Java
C++

student = {
    'StuA': 'Python',
    'StuB': 'Java',
    'StuC': 'Java',
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for value in set(student.values()):
        file_object.write(value)
        file_object.write('\n')

输出:(result.txt) 
Java
Python

3.嵌套

字典列表:

student1 = {'name': 'Python', 'age': 10}
student2 = {'name': 'Java', 'age': 15}
student3 = {'name': 'C++', 'age': 20}

students = [student1, student2, student3]

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for student in students:
        file_object.write(student['name'])
        file_object.write(' ')
        file_object.write(str(student['age']))
        file_object.write('\n')

输出:(result.txt) 
Python 10
Java 15
C++ 20

在字典中存储列表:

student = {
    'name': 'Python', 
    'food': ['rice', 'noodle', 'meat'],
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(student['name'])
    file_object.write(' ')
    for item in student['food']:
        file_object.write(item)
        file_object.write(' ')

输出:(result.txt) 
Python rice noodle meat 

在字典中存储字典:

student = {
    'name': 'Python', 
    'extra': {
        'first': 'red',
        'second': 'blue',
        'third': 'green',
        },
    }

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(student['name'])
    file_object.write(' ')
    for value in student['extra'].values():
        file_object.write(value)
        file_object.write(' ')

输出:(result.txt) 
Python red blue green 

七、用户输入和while循环

1.用户输入

函数input()的使用:

name = input("What's your name?")

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(name)

输出:(result.txt) 
Python

使用int()来获取数值输入:

age = input("How old are you?")

filename = 'result.txt'
with open(filename, 'w') as file_object:
    age = int(age)
    if age > 20:
        file_object.write('age > 20')
    else:
        file_object.write('age <= 20')  
        
输出:(result.txt) 
age > 20

求模运算符:

number = 4 % 3

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(number))

输出:(result.txt) 
1

2.while循环

使用while循环:

message = input('input message: ')

filename = 'result.txt'
with open(filename, 'w') as file_object:
    while message != 'quit':
        file_object.write(message)
        file_object.write('\n')
        message = input('input message: ')
    
输出:(result.txt) 
hello
python
tomy

使用break退出循环:

filename = 'result.txt'
with open(filename, 'w') as file_object:
    while True:
        message = input('input message: ')
        if message == 'quit':
            break;
        file_object.write(message)
        file_object.write('\n')

输出:(result.txt) 
hello
python

在循环中使用continue:

number = 0

filename = 'result.txt'
with open(filename, 'w') as file_object:
    while number < 10:
        number += 1
        if number % 2 == 0:
            continue
        file_object.write(str(number))
        file_object.write('\n')

输出:(result.txt) 
1
3
5
7
9

使用while循环来处理列表和字典:

names = ['Aaa', 'Bbb', 'Ccc']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    while names:
        name = names.pop()
        file_object.write(name)
        file_object.write('\n')

输出:(result.txt) 
Ccc
Bbb
Aaa

删除包含特定值的所有列表元素:

names = ['Aaa', 'Bbb', 'Ccc', 'Bbb', 'Bbb']

filename = 'result.txt'
with open(filename, 'w') as file_object:
    while 'Bbb' in names:
        names.remove('Bbb')
    for name in names:
        file_object.write(name)
        file_object.write('\n')

输出:(result.txt) 
Aaa
Ccc

八、函数

1.定义函数

向函数传递信息:

def method(username):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(username)

method('Python')

输出:(result.txt) 
Python

2.传递实参

位置实参:

def method(username, age):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(username)
        file_object.write(' ')
        file_object.write(str(age))

method('Python', 12)

输出:(result.txt) 
Python 12

关键字实参:

def method(username, age):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(username)
        file_object.write(' ')
        file_object.write(str(age))

method(age=20, username='Java')

输出:(result.txt) 
Java 20

默认值:

def method(username, age=30):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(username)
        file_object.write(' ')
        file_object.write(str(age))

method('Java')

输出:(result.txt) 
Java 30

等效的函数调用:

def method(username, age=30):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(username)
        file_object.write(' ')
        file_object.write(str(age))

method('Java')
method(username='Java')
method('Java', 30)
method(username='Java', age=30)
method(age=30, username='Java')

3.返回值

简单返回值:

def method(username, age=30):
    return username + ' ' + str(age)

message = method('Java', 30)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(message)

输出:(result.txt) 
Java 30

让实参变成可选的:

def method(username, age=-1):
    if age == -1:
        return username
    else:
        return username + ' ' + str(age)

message = method('Java')

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(message)

输出:(result.txt) 
Java

返回字典:

def method(username, age=-1):
    if age == -1:
        return {'username': username}
    else:
        return {'username': username, 'age': age}

person = method('Java', 20)

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for key, value in person.items():
        file_object.write(key + ' ' + str(value))
        file_object.write('\n')

输出:(result.txt) 
username Java
age 20

4.传递列表

将列表传递给函数:

def method(names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        for name in names:
            file_object.write(name)
            file_object.write(' ')

names = ['Android', 'Java', 'Python']
method(names)

输出:(result.txt) 
Android Java Python 

在函数中修改列表:

def method(names):
    names[0] = 'C++'
    
names = ['Android', 'Java', 'Python']
method(names)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    for name in names:
        file_object.write(name)
        file_object.write(' ')

输出:(result.txt) 
C++ Java Python 

禁止函数修改列表:

def method(names):
    names[0] = 'C++'

names = ['Android', 'Java', 'Python']
method(names[:])
filename = 'result.txt'
with open(filename, 'w') as file_object:
    for name in names:
        file_object.write(name)
        file_object.write(' ')

输出:(result.txt) 
Android Java Python 

5.传递任意数量的实参

使用任意数量的实参:(形参名添加一个星号,表示空元组)

def method(*names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        for name in names:
            file_object.write(name)
            file_object.write(' ')

method('Python', 'Java', 'C++', 'Android')

输出:(result.txt) 
Python Java C++ Android 

结合使用位置实参和任意数量实参:

def method(city, *names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(city)
        file_object.write('\n')
        for name in names:
            file_object.write(name)
            file_object.write(' ')

method('city', 'Python', 'Java', 'C++', 'Android')

输出:(result.txt) 
city
Python Java C++ Android 

使用任意数量的关键字实参:(形参名添加两个星号,表示空字典)

def method(city, **student):
    profile = {}
    profile['city'] = city
    for key, value in student.items():
        profile[key] = value
    return profile

user_profile = method('city', name='StuA', language='Python')
filename = 'result.txt'
with open(filename, 'w') as file_object:
    for key, value in user_profile.items():
        file_object.write(key)
        file_object.write(' ')
        file_object.write(value)
        file_object.write('\n')

输出:(result.txt) 
city city
name StuA
language Python

6.将函数存储在模块中

导入整个模块:(模块是扩展名为.py的文件,包含要导入到程序中的代码)

test_method.py:
def method(city, *names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(city)
        file_object.write('\n')
        for name in names:
            file_object.write(name)
            file_object.write(' ')
            
hello_python.py:
import test_method

test_method.method('city', 'Python', 'Java', 'C++', 'Android')

输出:(result.txt) 
city
Python Java C++ Android 

导入特定的函数:

test_method.py:
def method(city, *names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(city)
        file_object.write('\n')
        for name in names:
            file_object.write(name)
            file_object.write(' ')

def method2():
    print('This is method2')

hello_python.py:
from test_method import method, method2

method('city', 'Python', 'Java', 'C++', 'Android')
method2()

输出:(result.txt) 
city
Python Java C++ Android 

使用as给函数指定别名:(类似于外号,解决名称冲突问题)

test_method.py:
def method(city, *names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(city)
        file_object.write('\n')
        for name in names:
            file_object.write(name)
            file_object.write(' ')
            
hello_python.py:
from test_method import method as new_method

def method():
    print('This is method')

new_method('city', 'Python', 'Java', 'C++', 'Android')

输出:(result.txt) 
city
Python Java C++ Android 

使用as给模块指定别名:

test_method.py:
def method(city, *names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(city)
        file_object.write('\n')
        for name in names:
            file_object.write(name)
            file_object.write(' ')

hello_python.py:
import test_method as m

def method():
    print('This is method')

m.method('city', 'Python', 'Java', 'C++', 'Android')

输出:(result.txt) 
city
Python Java C++ Android 

导入模块中的所有函数:(不建议)

test_method.py:
def method(city, *names):
    filename = 'result.txt'
    with open(filename, 'w') as file_object:
        file_object.write(city)
        file_object.write('\n')
        for name in names:
            file_object.write(name)
            file_object.write(' ')

def method2():
    print('This is method2')

hello_python.py:
from test_method import *

method('city', 'Python', 'Java', 'C++', 'Android')
method2()

输出:(result.txt) 
city
Python Java C++ Android 

九、类

1.创建和使用类

class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

my_dog = Dog('Bily', 9)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
my_dog.sit()
my_dog.roll_over()

输出:(result.txt) 
Bily 9

2.使用类和实例

给属性指定默认值:

class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name):
        """初始化属性name和age"""
        self.name = name
        self.age = 0

my_dog = Dog('Bily')
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))

输出:(result.txt) 
Bily 0

修改属性的值:

class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name):
        """初始化属性name和age"""
        self.name = name
        self.age = 0

my_dog = Dog('Bily')
my_dog.age = 21
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))

输出:(result.txt) 
Bily 21
class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name):
        """初始化属性name和age"""
        self.name = name
        self.age = 0

    def update_age(self, age):
        """更新age"""
        self.age = age

my_dog = Dog('Bily')
my_dog.update_age(32)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))

输出:(result.txt) 
Bily 32

3.继承

给子类定义属性和方法:

class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

class ElectricDog(Dog):
    """电动狗"""
    
    def __init__(self, name, age, money):
        """初始化父类的属性"""
        super().__init__(name, age)
        self.money = money

    def get_money(self):
        return self.money

my_dog = ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))

输出:(result.txt) 
Bily 12 2000

重写父类的方法:

class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

class ElectricDog(Dog):
    """电动狗"""
    
    def __init__(self, name, age, money):
        """初始化父类的属性"""
        super().__init__(name, age)
        self.money = money

    def get_money(self):
        return self.money
        
    def sit(self):
        print('ElectricDog sit')
    

my_dog = ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))
my_dog.sit()

输出:(result.txt) 
Bily 12 2000

将实例用作属性:

class Dog():
    """一次模拟小狗的简单尝试"""
    
    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

class Battery():
    """一次模拟电池的简单尝试"""
    
    def __init__(self, battery_size=70):
        self.battery_size = battery_size

class ElectricDog(Dog):
    """电动狗"""
    
    def __init__(self, name, age, money):
        """初始化父类的属性"""
        super().__init__(name, age)
        self.money = money
        self.battery = Battery()

    def get_money(self):
        return self.money
        
    def sit(self):
        print('ElectricDog sit')
    

my_dog = ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))
    file_object.write(' ')
    file_object.write(str(my_dog.battery.battery_size))

输出:(result.txt) 
Bily 12 2000 70

4.导入类

导入单个类:

dog.py:
class Dog():

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

hello_python.py:
from dog import Dog

my_dog = Dog('Dream', 2020)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))

输出:(result.txt) 
Dream 2020

从一个模块中导入多个类:

dog.py:
class Dog():
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

class Battery():

    def __init__(self, battery_size=70):
        self.battery_size = battery_size

class ElectricDog(Dog):

    def __init__(self, name, age, money):
        super().__init__(name, age)
        self.money = money
        self.battery = Battery()

    def get_money(self):
        return self.money
        
    def sit(self):
        print('ElectricDog sit')

hello_python.py:
from dog import Dog, Battery, ElectricDog

my_dog = ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))
    file_object.write(' ')
    file_object.write(str(my_dog.battery.battery_size))

输出:(result.txt) 
Bily 12 2000 70

导入整个模块:

dog.py:
class Dog():
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

class Battery():

    def __init__(self, battery_size=70):
        self.battery_size = battery_size

class ElectricDog(Dog):

    def __init__(self, name, age, money):
        super().__init__(name, age)
        self.money = money
        self.battery = Battery()

    def get_money(self):
        return self.money
        
    def sit(self):
        print('ElectricDog sit')

hello_python.py:
import dog

my_dog = dog.ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))
    file_object.write(' ')
    file_object.write(str(my_dog.battery.battery_size))

输出:(result.txt) 
Bily 12 2000 70

导入模块中的所有类:(不推荐)

dog.py:
class Dog():
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

class Battery():

    def __init__(self, battery_size=70):
        self.battery_size = battery_size

class ElectricDog(Dog):

    def __init__(self, name, age, money):
        super().__init__(name, age)
        self.money = money
        self.battery = Battery()

    def get_money(self):
        return self.money
        
    def sit(self):
        print('ElectricDog sit')

hello_python.py:
from dog import *

my_dog = ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))
    file_object.write(' ')
    file_object.write(str(my_dog.battery.battery_size))

输出:(result.txt) 
Bily 12 2000 70

在一个模块中导入另一个模块:

dog.py:
class Dog():
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print('Dog sit')
        
    def roll_over(self):
        print('Dog roll over')

electric_dog.py:
from dog import Dog

class Battery():

    def __init__(self, battery_size=70):
        self.battery_size = battery_size

class ElectricDog(Dog):

    def __init__(self, name, age, money):
        super().__init__(name, age)
        self.money = money
        self.battery = Battery()

    def get_money(self):
        return self.money
        
    def sit(self):
        print('ElectricDog sit')

hello_python.py:
from dog import Dog
from electric_dog import ElectricDog

your_dog = Dog('Green', 8)
my_dog = ElectricDog('Bily', 12, 2000)
filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(your_dog.name)
    file_object.write(' ')  
    file_object.write(str(your_dog.age))
    file_object.write('\n')
    file_object.write(my_dog.name)
    file_object.write(' ')
    file_object.write(str(my_dog.age))
    file_object.write(' ')
    file_object.write(str(my_dog.get_money()))
    file_object.write(' ')
    file_object.write(str(my_dog.battery.battery_size))

输出:(result.txt) 
Green 8
Bily 12 2000 70

5.Python标准库

Python标准库是一组模块,安装的Python都包含它。例如,要创建字典并记录其中的键-值对的添加顺序,可使用模块collections中的OrderedDict类。OrderedDict实例的行为几乎与字典相同,区别只在于记录了键-值对的添加顺序。

from collections import OrderedDict

favorite_language = OrderedDict()

favorite_language['jen'] = 'python'
favorite_language['sarah'] = 'c'
favorite_language['edward'] = 'ruby'
favorite_language['phil'] = 'python'

filename = 'result.txt'
with open(filename, 'w') as file_object:
    for name, language in favorite_language.items():
        file_object.write(name)
        file_object.write(' ')
        file_object.write(language) 
        file_object.write('\n')

输出:(result.txt) 
jen python
sarah c
edward ruby
phil python

十、文件和异常

1.从文件中读取数据

读取整个文件:

filename = 'result.txt'
with open(filename) as file_object:
    contents = file_object.read()
    print(contents)

相对文件路径:

filename = 'mypath\myresult.txt'
with open(filename) as file_object:
    contents = file_object.read()
    print(contents)

绝对文件路径:

filename = 'D:\geany\workspace\mypath\myresult.txt'
with open(filename) as file_object:
    contents = file_object.read()
    print(contents)

逐行读取:

filename = 'result.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

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

filename = 'result.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
    
for line in lines:
    print(line.rstrip())

使用文件内容:

filename = 'result.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
    
value = int(lines[0]) + int(lines[1]) + float(lines[2])
print(value)

包含一百万位的大型文件:

对于你可处理的数据量,Python没有任何限制,只要系统的内存足够多,你想处理多少数据都可以。

2.写入文件

打开文件:

打开文件时,可指定读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。如果省略了模式实参,Python将以默认的只读模式打开文件。

如果写入的文件不存在,函数open()将自动创建它。然而,以写入('w')模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。

写入多行:

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write('line 1\n')
    file_object.write('line 2\n')
    file_object.write('line 3')

输出:(result.txt) 
line 1
line 2
line 3

附加到文件:

filename = 'result.txt'
with open(filename, 'a') as file_object:
    file_object.write('\nHello Python\n')
    file_object.write('I am Android')

输出:(result.txt) 
line 1
line 2
line 3
Hello Python
I am Android

3.异常

处理ZeroDivisionError异常:(使用try-except代码块)

try:
    value = 5 / 0
except ZeroDivisionError:
    value = -1

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(value))

输出:(result.txt) 
-1

else代码块:

try:
    value = 5 + 5 
except ZeroDivisionError:
    value = -1
else:
    value *= 2

filename = 'result.txt'
with open(filename, 'w') as file_object:
    file_object.write(str(value))

输出:(result.txt) 
20

处理FileNotFoundError异常:

try:
    filename = 'testresult.txt'
    with open(filename) as file_object:
        file_object.write(str(value))
except FileNotFoundError:
    print('file not found')

分析文本:

try:
    filename = 'result.txt'
    with open(filename) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    print('file not found')
else:
    words = contents.split()
    number = len(words)
    print(number)

失败时一声不吭:

try:
    filename = 'result.txt'
    with open(filename) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    pass
else:
    words = contents.split()
    number = len(words)
    print(number)

4.存储数据

使用json.dump():

import json

numbers = [2, 3, 5, 7, 11, 13]

filename = 'number.json'
with open(filename, 'w') as file_object:
    json.dump(numbers, file_object)

输出:(number.json)    
[2, 3, 5, 7, 11, 13]

使用json.load():

import json

filename = 'number.json'
with open(filename) as file_object:
    numbers = json.load(file_object)

print(numbers)

十一、测试代码

1.测试函数

单元测试和测试用例:

Python标准库中的模块unittest提供了代码测试工具。

单元测试用于核实函数的某个方面没有问题。

测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。

全覆盖式测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式。

可通过的测试:

要为函数编写测试用例,可先导入模块unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。

test_method.py:
def get_message(city, name):
    message = city + ' ' + name
    return message.title()

hello_python.py:
import unittest
from test_method import get_message

class MessageTestCase(unittest.TestCase):
    """测试test_method.py"""
    
    def test_get_message(self):
        """能够正确地处理Guangzhou Tom信息吗?"""
        message = get_message('guangzhou', 'tom')
        self.assertEqual(message, 'Guangzhou Tom')

unittest.main()

不能通过的测试:

test_method.py:
def get_message(city, name):
    message = city + ' ' + name
    return message.title()

hello_python.py:
import unittest
from test_method import get_message

class MessageTestCase(unittest.TestCase):
    """测试test_method.py"""
    
    def test_get_message(self):
        """能够正确地处理GUANGZHOU TOM信息吗?"""
        message = get_message('guangzhou', 'tom')
        self.assertEqual(message, 'GUANGZHOU TOM')

unittest.main()

2.测试类

各种断言方法:

assertEqual(a, b):核实a == b
assertNotEqual(a, b):核实a != b
assertTrue(x):核实x为True
assertFalse(x):核实x为False
assertIn(item, list):核实item在list中
assertNotIn(item, list):核实item不在list中

一个要测试的类:

test_method.py:
class Message():

    def __init__(self):
        pass
        
    def get_short_name(self, first_name, last_name):
        message = first_name + ' ' + last_name
        return message.title()

    def get_full_name(self, first_name, middle_name, last_name):
        message = first_name + ' ' + middle_name + ' ' + last_name
        return message.title()

hello_python.py:
import unittest
from test_method import Message

class MessageTestCase(unittest.TestCase):
    
    def test_get_short_name(self):
        message_object = Message()
        message = message_object.get_short_name('jim', 'green')
        self.assertEqual(message, 'Jim Green')

unittest.main()

方法setUp():(先运行setUp()方法,再运行各个test打头的方法)

test_method.py:
class Message():

    def __init__(self):
        pass
        
    def get_short_name(self, first_name, last_name):
        message = first_name + ' ' + last_name
        return message.title()

    def get_full_name(self, first_name, middle_name, last_name):
        message = first_name + ' ' + middle_name + ' ' + last_name
        return message.title()

hello_python.py:
import unittest
from test_method import Message

class MessageTestCase(unittest.TestCase):
    
    def setUp(self):
        self.message_object = Message()
    
    def test_get_short_name(self):
        message = self.message_object.get_short_name('jim', 'green')
        self.assertEqual(message, 'Jim Green')

    def test_get_full_name(self):
        message = self.message_object.get_full_name('jim', 'middle', 'green')
        self.assertEqual(message, 'Jim Middle Green')
        
unittest.main()

相关文章

网友评论

    本文标题:Python基础

    本文链接:https://www.haomeiwen.com/subject/vlascktx.html