Fork Me

记录学习Python

《Python编程从入门到实践》

记录学习,《Python编程从入门到实践》,一书中的基础知识。

2.变量和数据类型

1
2
3
4
5
6
7
8
9
10
message = "hello python world"
print(message)
name = 'chouxk top'
#首字母大写
name.title()
#全部小写
name.lower()
#全部大写
name.upper()

列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#列表
name = ['chouxk','python','php','java']
#表示最后一个元素
name[-1]
#末尾添加新元素
name.append('javascript')
#任意位置添加元素
name.insert(1,'ducati')
#删除元素
del name[0]
del name[-1]
#删除最后一个元素,并返回该元素
name.pop()
#删除任意索引元素,并返回该元素
name.pop(2)
#删除指定元素值
#remove 只删除列的第一个指定值
name.remove('chouxk')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
web = ['blibli','acf','pixiv','google','baidu']
#反转列表,没有返回值
web.reverse()
print(web)
#按字母顺序永久排序
web.sort()
#按字母倒序永久排序
web.sort(reverse = True)
#临时顺序排序
print(sorted(web))
#临时倒序排序
print(sorted(web,reverse=True))

4.操作列表

遍历列表

1
magicians = ['alice','david','carolina']
  • 循环过程:
    1. 获取magicians中第一个元素,存储都变量magician中。
    2. 执行print(第一个元素)。
  • 使用循环,对列表中的每一个元素,执行循环动作,假如有100w个元素,Python重复执行100w次。
1
2
3
4
5
6
# 注意勿冒号
for magician in magicians:
# print(magician)
print(magician + "that was a great trick")
# 注意缩进,此处没有缩进,属于循环外
print("Thank you,everyone.")

创建数值列表

1
2
3
4
5
6
7
8
# range(),第一个值为开始值,达到第二值停止,但不包含第二个值
for value in range(1, 5):
print(value)
# list(rang(1,6))输出数字列
number1 = list(range(1, 6))
# 参数三,为增加值
number2 = list(range(1, 11, 2))
print(number2)

1-10的整数平方的列表

1
2
3
4
5
6
7
8
9
squares = []
for value in range(1, 11):
square = value ** 2;
squares.append(square)
print(squares)
print('最小值:' + str(min(squares)))
print('最大值:' + str(max(squares)))
print('总数值:' + str(sum(squares)))

列表解析

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

列表切片

1
2
3
4
5
6
players = ['chouxk','baidu','google','sogou','bing']
#参数1:开始的切片位置,参数2:最终切片的位置(非索引)。切片个数=参数2-参数1
print(players[2:4])
print(players[:3])
print(players[3:])
print(players[-2:])

遍历切片

1
2
3
players = ['chouxk', 'martian', 'michael', 'florence', 'eli']
for player in players[:3]:
print(player)

复制列表

1
2
3
my_foods = ['pizza','hot dog','bread','cake']
#省略起始索引和终止索引,等于复制了整个列表
friend_foods = my_foods[:]

元组

Python将不能修改的值称为不可改变的,而不可改变的列表称为元组

使用圆括号标识:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dimensions = ('Chouxk', 'me')
print(dimensions[0])
for val in dimensions:
print(val)
# 不能修改元组元素
# 但可以给元组赋值
dimensions = (100, 123)
for val in dimensions:
print(val)
dimensions = (123, 123)
for val in dimensions:
print(val)

5.if语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cars = ['audi', 'bmw', 'subaru', 'toyota']
# Python不要求if-elif结构后必须有else代码块
for car in cars:
if car == "bmw":
print(car.upper())
elif car == 'audi':
print(car.lower())
else:
print(car.title())
if 'audi' in cars:
print('检测值是否在列表中,This is True')
# 区分大小写
Bmw = 'Bmw'
if Bmw not in cars:
print('检测值是否在列表中,This is True')
# 使用if语句处理列表
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print('Sorry,we are out of green peppers right now.')
else:
print("Adding " + requested_topping + '.')

##6.字典

字典

  1. Python字典是一系列键-值对。

  2. 与键相关的值可以是数字,字符串,列表,字典

  3. 字典使用花括号{}标识

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
alien_0 = {'color':'green','points':5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
alien_1 = {}
alien_1['color'] = 'red'
alien_1['points'] = 20
alien_1['x_position'] = 101
alien_1['y_position'] = 10
#删除
del alien_1['color']
print(alien_1)

遍历字典

遍历字典,键值对的返回顺序和存储顺序不同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#遍历字典,键值对的返回顺序和存储顺序不同
#items()返回可遍历的(键,值)元组数组
#key,val是名称可以自定义的
for key,val in me.items():
print('\nkey:' + key)
print('val:' + val)
print('--------------------------------')
#keys()返回一个全部键名的列表,values()同理
if 'Chouxk.me' not in me.values():
print('是的呢!')
#默认遍历所以的键
for key in me:
print('key: '+str(key.title()))
#亦可以
for key in me.keys():
print('key: '+str(key.title()))

字典嵌套

字典列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','point':5,'speed':'slow'}
aliens.append(new_alien)
print(len(aliens))
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = '10'
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = '15'
for alien in aliens[:6]:
print(alien)

在字典中存储列表

1
2
3
4
5
6
7
8
9
pizza = {
'crust':'thick',
'toppings': ['mushrooms','extra cheese'],
}
print("You ordered a " +pizza['crust'] + '-crust pizza' + 'with the following toppings:')
for topping in pizza['toppings']:
print("\t"+topping)

在字典中存储字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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())

7.用户输入和while循环

使用input

1
2
3
4
5
6
number = input('请输入:')
number = int(number)
if number % 2 == 0:
print('偶数')
else:
print('奇数')

使用标志或break

1
2
3
4
5
6
7
8
9
10
11
12
13
14
prompt = "\n如果要退出请输入'exit'"
prompt += "\n请输入: "
sign = True
message = ''
while sign:
message = input(prompt)
if message == 'exit':
print('退出成功!\n')
# 或者使用break退出
break
# sign = False
else:
print(message)

使用continue

1
2
3
4
5
6
7
#打印1-10的奇数
current_num = 0;
while current_num < 10:
current_num += 1;
if current_num % 2 == 0:
continue
print(current_num)

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

1
2
3
4
5
6
7
8
9
10
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
confirmed_users.append(current_user)
print('verifying user:' + current_user.title())
print('\nThe follwing users have been confirmed:')
for confirmed_user in confirmed_users:
print(confirmed_user)

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

1
2
3
4
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
while 'cat' in pets:
pets.remove('cat')

使用用户输入来填充字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
responses = {}
polling_active = True
while polling_active:
name = input('请输入你的名字:')
response = input('请输入你的答案:')
responses[name] = response
repeat = input("查看是否还有人参与回答")
if repeat == "no":
polling_active = False
print('\n--- Poll Results ---')
for name,response in responses.items():
print(name + ",你的答案是:" + response+'.')

8.函数

定义函数

1
2
3
def hello(username):
"""显示你好世界"""
print('Hello,world,' + username.title() + '!')

传递列表或元组

1
2
3
4
5
6
7
8
def get_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
print('hello' + ',' + name)
users = ['hxk','top','tom','jokey']
users = ('top','hxk','tom','jokey')
get_users(users)

传递任意数量的实参

*topping 创建一个名为topping的空元组,并将所有收到的值都封装在这个元组中。

1
2
3
4
5
6
7
8
9
10
11
12
13
def pizza_topping(*topping):
"""打印顾客点的所有配料"""
print(topping)
# pizza_topping('pepperoni','cheese','barbecue')
#结合使用位置实参和任意数量实参
def make_pizza(size,*topping):
"""概述要制作的披萨"""
print('Make ' + str(size) + ' pizza with the following topping: ')
for val in topping:
print(val)
# make_pizza(12,'pepperoni','cheese','barbecue')

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

形参**user_info,创建一个名为user_info的空字典,并将收到的所有名称键-值对封装到这个字典中

1
2
3
4
5
6
7
8
9
10
11
12
def buid_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key,val in user_info.items():
profile[key] = val
return profile
user_profile = buid_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

导入整个模块

1
2
3
4
5
6
7
#pizza.py模块文件
def make_pizza(size,*topping):
"""概述要制作的披萨"""
print('Make ' + str(size) + ' pizza with the following topping: ')
for val in topping:
print(val)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#方法一
import pizza
pizza.make_pizza(12,'pepperoni')
#给模块指定别名
import pizza as p
p.make_pizza(12,'pepperoni')
#方法二
from model_name import function_name
#如:
from pizza import make_pizza
make_pizza(12,'pepperoni')
#如果导入的函数名称与程序中现有名称冲突,或者函数名称过长,使用as 指定别名
from pizza import make_pizza as mp
make_pizza(12,'pepperoni')
#方法三
#导入模块中的所有函数(不推荐使用)
from pizza import *

9.类

Dog类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now siting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " roll over.")
my_dog = Dog('jokey', 3)
print('My dog name is ' + str(my_dog.name.title()))
print('he is ' + str(my_dog.age) + ' years old')
my_dog.sit()
my_dog.roll_over()

car类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Car():
"""这个是我创造的汽车"""
def __init__(self, make, model, year):
"""初始化"""
self.make = make
self.model = model
self.year = year
self.odometer = 20
def get_description(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))
def update_odometer(self, num):
"""设置里程值,禁止里程值回调"""
if num >= self.odometer:
self.odometer = num
else:
print('我去,回调了,怎么可能!')
def add_odometer(self, num):
"""递增里程"""
self.odometer += num
# my_new_car = Car('bmw','a4','2019')
# print(my_new_car.get_description())
#
# # 直接设置值
# my_new_car.odometer = 20
# #方法设置值
# my_new_car.update_odometer(21)
# my_new_car.add_odometer(10)
#
# my_new_car.read_odometer()
# 定义battery类
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(80);
def read_odometer(self):
"""重写方法"""
print(self.make, '重写');
my_tesla = ElectricCar('tesla', 'models', '2017')
my_tesla.battery.describe_battery();
my_tesla.read_odometer();

10.文件和异常

文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from collections import Counter
file_name = 'digits.txt'
with open(file_name) as file_obj:
line = file_obj.readline()
# print(line)
# print(line.rstrip())
pi_string = ''
for lines in line:
pi_string += lines.strip()
print(pi_string[:52] + '...')
print(len(pi_string))
print('---------------------------------')
with open(file_name) as file_obj:
for line in file_obj:
c = Counter(line.rstrip())
print(c.most_common())
1
2
3
4
5
6
7
8
9
10
11
filename = 'programing.txt'
# 写入文件
with open(filename, 'w') as obj:
obj.write('I love programing.\n')
obj.write('I write the coding.\n')
# 附加内容到文件
with open(filename, 'a') as obj:
obj.write('I the harder you work the luckier you\'ll be.\n')
obj.write('Existence is mission.\n')

异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 处理 ZeroDivisionError
try:
print(5 / 0)
except ZeroDivisionError:
print('You can\'t divide by zero!').
# 异常处理示例
while True:
first_number = input("\nFirst Number: ")
if first_number == 'q':
break
second_number = input("Second Number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except (ZeroDivisionError, ValueError):
print('You can\'t divide by zero or Value can\'t by empty')
else:
print(answer)
1
2
3
4
5
6
7
8
9
10
11
12
# 处理 FileNotFoundError
filename = 'programing.txt'
try:
with open(filename) as obj:
contents = obj.read()
except FileNotFoundError:
msg = ("Sorry, File " + filename + " does not exist")
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = ("Sorry, File " + filename + " does not exist")
print(msg)
# pass
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
# 计算多个文件
fileNames = ['a.txt', 'b.txt']
for file in fileNames:
count_words(file)

存储数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 使用json.dump()和json。load()
# 示例
import json
number = [2, 3, 21, 414, 14]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(number, f_obj)
with open(filename,'r') as obj:
data = json.load(obj);
print(data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 初始版
import json
def greet_user():
"""问候用户,并指出名字"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input('what is your name? ')
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back," + username + "!")
else:
print("Welcome back," + str(username) + "!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 进阶版
def get_stored_username():
"""如果储存了用户,就获取它"""
filename = 'username.json'
try:
with open(filename) as obj:
username = json.load(obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入用户名"""
username = input('what is your name? ')
filename = 'username.json'
with open(filename, 'w') as obj:
json.dump(username, obj)
return username
def get_username2():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back," + str(username) + "!")
else:
username = get_new_username()
print("We'll remember you when you come back," + username + "!")