《python编程从入门到实践》笔记(1)—20191121
第一部分 基础知识
chap1 搭建编程环境
chap2 变量和简单数据类型
1.变量的命名和使用
1)变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
2) 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greetingmessage会引发错误。 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print
3)变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。
4)慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。
注意:就目前而言,应使用小写的python变量名。
2.使用函数str()避免类型错误
3.python之禅
python社区的理念都包含在im Peters撰写的“python"之禅中。要获悉这些有关优秀python代码的指导原则,只需再解释器中输入命令 import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!
chap3 列表
列表添加元素方法:
1)在列表末尾添加元素,使用append(值)函数
2)在列表中插入元素:insert(索引,值)
从列表中删除元素:
1)使用del语句删除 del 列表[索引]
2)使用pop()方法 删除列表末尾的元素
3)根据值来删除元素:remove()方法:此方法只删除第一个指定的值,如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
组织列表
1)使用sort()方法对列表进行永久性排序;反向排序:list.sort(reverse = True)
2)使用soted()对列表进行临时排序:能够按照特定的顺序显示列表,同时不影响他们在列表中的原始排列顺序
3)反转列表:reverse()
4)确定列表的长度:len(list)
chap4
4.1 操作列表
1.遍历列表for i in list:
2.避免缩进错误
3.使用函数range()生成一系列的数字-左闭右开区间,从指定的第一个数值开始,并在达到你指定的第二个数后停止(范围不包含第二个值)
使用range()创建数字列表:list[range(1,5)]
range()还可以指定步长–第三个参数
#对列表的range()函数
#1.使用range()函数创建数字列表
numbers = list(range(1,6))
print(numbers)
#2.range()可以指定步长
even_numbers = list(range(2,11,2))
print(even_numbers)
#3.使用range()创建一个列表,包含前10个整数的平方
squares = []#建一个空列表
for value in range(1,11):
squares.append(value **2)
print(squares)
#4.对数字列表进行简单的数值计算
print(min(numbers))
print(max(numbers))
print(sum(numbers))
#5.列表介绍:将for循环和创建新元素的代码合并成1行,并自动附加新元素
squares1 = [value**2 for value in range(1,11)]
print(squares1)
运行结果:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1
5
15
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4.2切片
使用列表的一部分:称之为切片
#1.输出列表中的前三个元素
players = ['charies','martina','michael','florence','eli']
print(players[0:3])
#2.如果没有指定第一个索引,将自动从列表开头开始:
print(players[:4])
#3.#让切片终止于列表末尾:
print(players[2:])
#4.输出名单上的最后三名队员
print(players[-3:])
#5.复制列表
#5.1创建一个包含整个列表的切片
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
friend_foods.append("ice cream")
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
#如果使用“=”,只是将my_foods,freiebd_foods 指向同一个列表,都是引用
my_foods1 = ['pizza','falafel','carrot cake']
friend_foods1 = my_foods1
friend_foods1.append("ice cream")
print("My favorite foods are:")
print(my_foods1)
print("\nMy friend's favorite foods are:")
print(friend_foods1)
使用“=”,只是传递了变量引用,my_foods 和friends_food 式内存中列表的引用,实际上指向的是同一个列表,并没有产生新的列表
运行结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
4.3元组
元组非常适合用于存储程序运行期间可能变化的数据集。
列表是可修改的,这对于处理网站的用行列表或游戏中的角色列表至关重要。
然而,有时候需要创建一系列不可修改的元素,元组可以满足这种需求。
python将不能修改的值称为不可变的,而不可变的列表被称为元组。
元组与列表定义的区别:
元组是()括号定义,列表是[]定义。定义元组后,可以是哦那个索引来访问其元素,就像访问列表元素一样。
#元组
#1.定义元组
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
#2.遍历元组中的值
for dimension in dimensions:
print(dimension,end = ' ')
#3.修改元组的变量
"""不能修改元组的元素,但可以给存储元组的变量赋值,
因此,如果要修改前述矩形的尺寸,可重新定义整个元组"""
dimensions = (400,100)
print("modeified deimensions:")
for dimension in dimensions:
print(dimension)
运行结果:
200
50
200 50 modeified deimensions:
400
100
4.4 设置代码格式PEP6
1)缩进:4个空格
2)行长:不超过80个字符,注释的行长不超过72个字符
3)空行:程序的不同部分分开,可使用空行,
《python编程从入门到实践》笔记(2) ----20191122
chap5 if语句
1.检查多个条件 and or
2.检查特定值是否包含在列表中: in not in
#1.检查特定值是否包含在列表中:
requesed_toppings = ['mushrooms','onions','pineapple']
print('mushrooms' in requesed_toppings)
print('mushrooms' not in requesed_toppings)
#2.if elif else
""""
检查超过两个的情形:依次检查每个条件测试,直到遇到通过的条件测试
python将执行紧跟在它后面的代码,并跳过余下的测试,可以省略else模块
"""
age = 12
if age <4:
price = 0
elif age <18:
price = 5
elif age <65:
price = 10
elif age >= 65:
price = 5
print("You admissin cost ids $ "+str(price)+".")
#3.使用if语句处理列表
#3.1检查特殊元素
requesed_toppings = ['mushrooms','green peppers','extra cheese']
for requesed_topping in requesed_toppings:
if requesed_topping == 'green peppers':
print("Sorry,We are ot of green peppers right now")
else:
print("Adding" + requesed_topping +".")
print("\nFinished making yor pizza!")
#3.2确定列表不是空的
requesed_topping1 = []
if requesed_topping1:
for requesed_topping in requesed_topping1:
print("Adding" + requesed_topping + ".")
print("\nFinished making yor pizza!")
else:
print("\nAre you sure you want a plain pizza?")
#3.3使用多个列表
avaliable_toppomgs = ['mushrooms','olives','green peppers',
'pepperoni','pineapple','extra cheese']
requesed_toppings = ['mushrooms','french fries','extra cheese']
for requesed_topping in requesed_toppings:
if requesed_topping in avaliable_toppomgs:
print("Adding"+ requesed_topping+'.')
else:
print("sorry ,we don't have "+requesed_topping+".")
print("\nFinished making yor pizza!")
运行结果:
True
False
You admissin cost ids $ 5.
Addingmushrooms.
Sorry,We are ot of green peppers right now
Addingextra cheese.
Finished making yor pizza!
Are you sure you want a plain pizza?
Addingmushrooms.
sorry ,we don't have french fries.
Addingextra cheese.
Finished making yor pizza!
本文深入浅出地讲解了Python编程的基础知识,包括环境搭建、数据类型、变量命名规范、列表和元组的操作、条件语句等核心概念,适合初学者快速上手。
173

被折叠的 条评论
为什么被折叠?



