目录
- 第一章 环境搭建
-
- 安装python环境
- 第二章:变量和简单数据类型
-
- 2.1第一个hello world!!! 入坑了
- 2.2 变量
- 2.3字符串
-
- 使用.title()方法修改单词的大小写
- 合并字符串
-
- 添加空白
- 删除空白--尾部-rstrip()
- 删除空白两端-lstrip()、strip()
- 2.4整数
-
- 函数str避免类型错误
- 2.5注释 (#)或 //
- 第三章:列表简介(数组)
-
- 3.1 访问列表元素&&使用列表中的各个值
- 3.2修改、添加和删除元素
-
- 修改元素
- 末尾添加元素append()
- 插入元素insert()
- 删除元素del()、pop()(弹出)
- 根据值删除元素remove()
- 3.3组织列表
-
- 永久性排序sort()
- 临时性排序sorted()
- 倒着打印列表reverse()
- 列表的长度len()
- 第四章:操作列表
-
- 遍历整个列表for
- 创建数值列表range()
-
- 创建数字列表list()+range()
- 统计计算最大值max()、最小值min()和总和sum()
- 列表解析
- 使用列表的一部分
- 遍历切片
- 复制列表
- 错误复制列表
- 创建一个不可变数组(元组)
- 重定义元组
- 第五章:if语句详解
-
- 一个简单示例
- 检查是否不相等
- 比较数字
- and 和or(相当于C语言&&和||)
- 检查特定值是否包含在列表中(可使用关键字in)
- 检查特定值是否不包含在列表中(not in)
- 布尔表达式
- if-else 语句
- if-elif-else 结构
- 其他就是一些和列表的配合
- 第六章:字典 {}
-
- 案例访问字典元素
- 添加键 添 —值对
- 修改字典中的值
- 删除键 删 —值对
- 使用类似对象组成的字典
- 遍历字典使用for, 使用items()
- 遍历字典中的所有键,使用keys()方法
- 按顺序遍历字典中的所有键sorted()
- 遍历字典中的所有值,values(),使用set()剔除重复
- 嵌套:多个字典存在列表里
- 使用range() 生成了30个
- 在字典中存储列表
- 字典中存储字典
- 第 7 章 用户输入和 章 while 循环循
-
- 函数函 input()
- 数值输入int()
- while循环使用
- 使用使 break 退出循环
- 循环中使用 在 continue
- while 循环来处理列表和字典
- 删除包含特定值的所有列表元素remove()
- 第 8 章 函数
-
- 向函数传递信息
- 关键字实参
- 返回值
- 空字符串代参数
- 返回字典
- 传递列表
- 在函数中修改列表
- 禁止函数修改列表使用副本[:]
- 传递任意数量的实参使用 * 列表
- 传递任意数量的实参使用 ** 字典
第一章 环境搭建
- vscode:下载地址
安装python环境
打开vscode
安装python 前4个都安装
第二章:变量和简单数据类型
2.1第一个hello world!!! 入坑了
新建保存一个HelloWorld.py文件
2.2 变量
区别:和C比较 可以不用定义基本类型
message = "Hello Python world!"
print(message)
变量使用规范
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greetingmessage会引发错误。
- 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print (请参见附录A.4)。
- 变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。
- 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。
2.3字符串
引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。
使用.title()方法修改单词的大小写
C语言中方式其实就是函数
message = "hello Python world!"
print(message.title())
合并字符串
Python使用加号(+ )来合并字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
添加空白
如空格、制表符和换行符。可使用字符组合\t
删除空白–尾部-rstrip()
空白很重要,因为你经常需要比较两个字符串是否相同。例如,一个重要的示例是,在用户登录网站时检查其用户名。但在一些简单得多的情形下,额外的空格也可能令人迷 惑。
Python能够找出字符串开头和末尾多余的空白。
要确保字符串末尾没有空白,可使用方法rstrip() 。
注意!!!:这种删除只是暂时的,要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中
favorite_language = 'python '
favorite_language = favorite_language.rstrip()
print(favorite_language)
删除空白两端-lstrip()、strip()
lstrip() 开头
strip()两端
favorite_language = ' python '
favorite_language = favorite_language.strip()
print(favorite_language)
2.4整数
在Python中,可对整数执行加(+ )减(- )乘(* )除(/ )运算、乘方** 运算 。
函数str避免类型错误
数字和字符串一起使用时 需要将数字用str 进行转换
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
2.5注释 (#)或 //
# 向大家问好
print("Hello Python people!")
第三章:列表简介(数组)
列表列 由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有 任何关系
在Python中,用方括号([] )来表示列表
3.1 访问列表元素&&使用列表中的各个值
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
3.2修改、添加和删除元素
修改元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
末尾添加元素append()
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
插入元素insert()
需要指定新元素的索引和值
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
删除元素del()、pop()(弹出)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
del motorcycles[1]
print(motorcycles)
每当你使用pop() 时,被弹出的元素就不再在列表中了。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
根据值删除元素remove()
有时候,你不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
3.3组织列表
永久性排序sort()
字母顺序排列,列表中的所有值都是小写
再也无法恢复到原来的排列顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
按与字母顺序相反的顺序排列列表元素
只需向sort() 方法传递参数reverse=True
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
临时性排序sorted()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
倒着打印列表reverse()
reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
列表的长度len()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
第四章:操作列表
遍历整个列表for
这行代码让Python从列表magicians 中取出一个名字,并将其存储在变 量magician 中。最后,我们让Python打印前面存储到变量magician 中的名字
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
print(magician)
print('end')
每个缩进的代码行都是循环的一部分
建议:临时变量这样写和列表名称相似
for cat in cats:
for dog in dogs:
for item in list_of_items:
创建数值列表range()
函数range() 让Python从你指定的第一个值开始数,并在到达你指定的第二个值 后停止,因此输出不包含第二个值(这里为5)。
for value in range(1,5):
print(value)
创建数字列表list()+range()
要创建数字列表,可使用函数list() 将range() 的结果直接转换为列表。如果将range() 作为list() 的参数,输出将为一个数字列表
for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
统计计算最大值max()、最小值min()和总和sum()
min
max
sum
arange = list(range(1,10))
print(arange)
print(min(arange))
print(max(arange))
print(sum(arange))
列表解析
列表解析 列 将for 循环和创建新元素的代码合并成一行,并自动 附加新元素
在这个示例中,for 循环为for value in range(1,11) ,它将值 1~10提供给表达式value2 。请注意,这里的for 语句末尾没有冒号。**
squares = [value**2 for value in range(1,11)]
print(squares)
使用列表的一部分
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
没有指定第一个索引,Python将自动从列表开头开始
让切片终止于列表末尾,也可使用类似的语法
print(players[:4])
print(players[2:])
遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
复制列表
你经常需要根据既有列表创建全新的列表。
假设有一个列表,其中包含你最喜欢的四种食品,而你还想创建另一个列表,在其中包含一位朋友喜欢的所有食品。不过,你喜欢的食品,这位朋友都喜欢,因此你可以 通过复制来创建这个列表:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
错误复制列表
下方写法感觉就就是在一个地址进行数据操作,而不是复制之后进行操作
my_foods = ['pizza', 'falafel', 'carrot cake']
#这行不通
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
创建一个不可变数组(元组)
元组看起来犹如列表,但使用圆括号而不是方括号来标识
类似于const
dimensions = [200, 50]
dimensions[0] = 30
print(dimensions)
dimensions = (200, 50)
dimensions[0] = 30
print(dimensions)
出错
但是可以重新定义
# 向大家问好
print("Hello Python people!")
重定义元组
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
第五章:if语句详解
一个简单示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
检查是否不相等
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
比较数字
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
and 和or(相当于C语言&&和||)
answer = 17
if answer < 42 and answer < 31:
print("run !!!")
if answer < 42 or answer < 15:
print("run !!!")
检查特定值是否包含在列表中(可使用关键字in)
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings )
print('pepperoni' in requested_toppings )
检查特定值是否不包含在列表中(not in)
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' not in requested_toppings )
print('pepperoni' not in requested_toppings )
布尔表达式
在跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式
# 向大家问好
print("Hello Python people!")
if-else 语句
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
if-elif-else 结构
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
其他就是一些和列表的配合
第六章:字典 {}
在Python中,字典字 是一系列键—值对值 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将 任何Python对象用作字典中的值。
类似于C语言中 一个标识符对应一个值
案例访问字典元素
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
添加键 添 —值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
创建一个空字典
alien_0 = {}
修改字典中的值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
删除键 删 —值对
对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
使用类似对象组成的字典
定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐。另外一种不错的做法是在最后一个键—值对后面也加上逗号,为以 后在下一行添加键—值对做好准备。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +".")
遍历字典使用for, 使用items()
for 语句的第二部分包含字典名和方法items() ,它返回一个键—值对列表。接下来,for 循环依次将每个键—值对存储到指定的两个变量中,下面是key、value。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key, value in favorite_languages.items():
print("key = "+key+"value = "+value)
遍历字典中的所有键,使用keys()方法
在不需要使用字典中的值时,方法keys() 很有用,处的代码行让Python提取字典favorite_languages 中的所有键,并依次将它们存储到变量key 中
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key in favorite_languages.keys():
print("key = "+ key)
下面也可以省略
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key in favorite_languages:
print("key = "+ key)
一样的!!!
按顺序遍历字典中的所有键sorted()
,但对方法dictionary.keys() 的结果调用了函数sorted() 。这让Python列出字典中的所有键,并在遍历前对这个列表进行排序。输出 表明,按顺序显示了所有被调查者的名字:
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
遍历字典中的所有值,values(),使用set()剔除重复
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in sorted(favorite_languages.values()):
print(name.title() + ", thank you for taking the poll.")
set
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in set(favorite_languages.values()):
print(name.title() + ", thank you for taking the poll.")
嵌套:多个字典存在列表里
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
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]
for alien in aliens:
print(alien)
使用range() 生成了30个
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
在字典中存储列表
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)
字典中存储字典
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()
函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用
函数input() 接受一个参数:即要向用户显示的提示提 或说明,让用户知道该如何做
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
数值输入int()
message = input("Tell me something, and I will repeat it back to you: ")
message = int(message)
print(message)
while循环使用
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
使用使 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() + "!")
循环中使用 在 continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
while 循环来处理列表和字典
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
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())
删除包含特定值的所有列表元素remove()
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
第 8 章 函数
❶处的代码行使用关键字def 来告诉Python你要定义一个函数。这是函数定义
函数调用 函 让Python执行函数的代码。要调用调 函数,可依次指定函数名以及用括号括起的必要信息
def greet_user():
"""显示简单的问候语"""
print("Hello!")
greet_user()
向函数传递信息
def greet_user(username):
"""显示简单的问候语"""
print("Hello!"+ username.title() + "!")
greet_user('dada')
关键字实参
其实就是传入参数赋值
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')
使用关键字实参时,务必准确地指定函数定义中的形参名
返回值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
空字符串代参数
Python将非空字符串解读为True
def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整洁的姓名"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
返回字典
def build_person(first_name, last_name):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
传递列表
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
在函数中修改列表
在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: " + current_design)
completed_models.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
禁止函数修改列表使用副本[:]
传递任意数量的实参使用 * 列表
有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
传递任意数量的实参使用 ** 字典
相当于可变数组 都集中在一个数组当中
def make_pizza(size, *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')