第一个程序 打印文本 print 函数也可以用来输出多行文本。
可以使用\n(换行符) 给文本换行,也可以使用多个 print  函数输出多行
print()  函数是会自带\n的
例如
1 2 print ('Hello world!' )print ('good\nbeauty ...' ) 
而如果我们想要没有换行 的话,可以使用end=''来解决这一问题
1 print ('Hello world!' ,end='' )
PS:会发现python的语法要求中并没有要求使用;来强制作为语句的结尾 
变量 在Python中的变量会根据赋予的值,来进行自动判断数据类型。
PS:字符串类型的变量可以通过*运算来输出打印的个数
变量可以随意多次重新赋值。 
在Python中,变量没有特定的类型,因此你可以将一个字符串分配给一个变量。
1 2 3 4 5 6 >>>  x = 123.456 >>>  print (x)123.456 >>>  x = "This is a string" >>>  print (x)This is  a string 
变量名称 Python变量名的命名有一些限制。
变量名称允许使用的字符是字母,数字和下划线。并且变量不能以数字开头。 
如果不遵守这些规则命名会导致错误。
1 2 3 >>>  this_is_a_normal_name = 7 >>>  123abc = 7 SyntaxError: invalid syntax 
并且Python作为一种高级语言,是会区分大小写的,因此设置变量是A,a就是两种变量
尝试引用尚未赋值的变量会导致错误 。
del语句 可以使用 del  语句来删除一个变量,这意味着从名称到值的引用被删除,并且尝试使用该变量会导致错误。
删除的变量可以像以前一样重新分配。
1 2 3 4 5 6 7 8 >>>  foo = "a string" >>>  foo'a string' >>>  barNameError: name 'bar'  is  not  defined >>>  del  foo>>>  fooNameError: name 'foo'  is  not  defined 
向变量中输入任意值 也可以从用户输入中获取变量的值。
1 2 3 4 >>>  foo = input ("Enter a number: " )Enter a number: 7  >>>  print (foo)7 
变量与常量 :命名规则 区分大小写赋值运算符 := += -= *= %= /= //=中文编码 :#-*- coding:UTF-8 -*- #coding=UTF-8 
数据类型 主要的数据类型有:整型 浮点型 字符串
type()查看数据类型 基本语法:type(查看类型的数据)
type()返回的值既可以 直接输出也可以 存储到变量中。
1 2 3 4 5 >>>print (type (114514 )) <class  'int' > >>>int_type = type (114514 ) >>print (int_type) <class  'int' > 
值得注意的是:变量无类型,但是存储的数据是有的  数据类型转换 基本语法:基本类型(x)
1 2 3 4 5 6 7 8 num_str = str (11 ) print (type (num_str),num_str)num = int ("114514" ) print (type (num),num)float_num = float (11 ) print (type (float_num),float_num)int_num = int (11.514 ) print (type (int_num),int_num)
1 2 3 4 <class  str > 11  <class  int > 114514  <class  float > 11.0  <class  int > 11  
字符串 字符串的定义 字符串就是一系列字符,在python中,用引号引起来的都是字符串,无论是单引号亦或是双引号
1 2 "Hello World" 'Hello World' 
因此这种灵活性,完全可以使字符串包含单引号或者双引号。
还有一种特殊的定义方式三引号定义法 
这种定义方式支持换行操作 ,这种方式与python的注释并不冲突。
在变量接收时,它就是字符串,没有变量接收时,就作为多行引用
1 2 3 4 name = """铅笔沫"""  """ 我是注释 """ 
字符串格式化 第一种方式 使用%占位
优点:可以进行精度控制 
缺点:书写起来速度较慢,且固定数据类型 
 
1 2 3 4 5 6 >>>name = "铅笔沫"  >>>message = "我是 %s"  % (name) 我是铅笔沫 
第二种方式 f"内容{变量}"
1 2 3 4 name = 铅笔沫 school = 哈尔滨理工大学 print (f"我是{name} ,我就读于{school} " )我是铅笔沫,我就读于哈尔滨理工大学 
字符串控制精度 与C/C++一致
除了
修改字符串的大小写 title() 将首字母大写的方式显示每个单词。
因此由title()修改过后的值会将,ADA,ADa,AdA,ada,Ada是为同一个名字Ada
upper() & lower() upper():将所有字母改写为大写
lower():将所有字母改写为小写
合并拼接字符串 可以使用 +  号连接任意两个字符串 ,连接字符串时,无论是使用单引号还是双引号创建的都可以。
1 2 3 4 5 >>>  "Spam"  + 'eggs' 'Spameggs' >>>  print ("First string"  + ", "  + "second string" )First string, second string 
即使字符串包含数字,它们仍然被添加为字符串而不是整数。将一个字符串加上数字中会产生一个错误 ,即使它们看起来相似,但它们是两个不同的实体。
1 2 3 4 5 6 7 print ("2"  + "2" )22 print (1  + '2'  + 3  + '4' )Traceback (most recent call last):   File "..\Playground\", line 3, in <module>      print(1 + '2' + 3 + '4') TypeError: unsupported operand type(s) for +: 'int' and 'str' 
因此我们可以通过使用str()来强制转换其类型 ,来避免这种错误
1 2 3 4 >>>age = 23   >>>message = "Happy "  + str (age) + "rd Birthday!"   >>>print (message) Happy 23rd Birthday!  
字符串也可以乘以整数 。这会产生原始字符串的重复版本。字符串和整数的顺序无关紧要,但字符串通常是放在前面的。
字符串不能与其他字符串相乘 。即使浮点数是整数,字符串也不能乘以浮点数。
1 2 3 4 5 6 7 print ("spam"  * 3 )print (4  * '2' )print ('17'  * '87' )print ('pythonisfun'  * 7.0 )
结果:
1 2 3 4 5 6 7 spamspamspam 2222 Traceback (most recent call last):   File "..\Playground\", line 5, in <module>      print('17' * '87') TypeError: can't multiply sequence by non-int of type 'str' 
删除空白 rstrip() 1 2 3 4 5 6 7 >>>  favorite_language = 'python ' >>>  favorite_language 'python '  >>>  favorite_language.rstrip()'python'  >>>  favorite_language'python ' 
要永久删除这个空白,需要将操作后的值返还到变量当中
1 2 3 4 >>>  favorite_language = 'python ' >>>  favorite_language = favorite_language.rstrip()>>>  favorite_language'python'  
lstrip() & strip() lstrip():删除开头空白
strrp():删除末尾空白
1 2 3 4 5 6 7 >>>  favorite_language = ' python ' >>>  favorite_language.rstrip()' python'  >>>  favorite_language.lstrip()'python '  >>>  favorite_language.strip() 'python'  
数字 整数 整数可执行+ - * / // % **运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 >>>  2  + 3 5  >>>  3  - 2 1  >>>  2  * 3 6  >>>  3  / 2 1.5  >>>9 //2   4 >>>4 %2 	 0 >>>4 **2 	 8 
在终端会话中,Python直接返回运算结果。Python使用两个乘号 表示乘方运算。
1 2 3 4 5 6 >>>  3  ** 2 9  >>>  3  ** 3 27  >>>  10  ** 6 1000000  
浮点数 通常上,使用浮点数时无需考虑其行为,python通常都会按照期望的样子处理,但是,结果所包含的小数位数可能使不确定的。 
1 2 3 4 5 6 7 8 9 10 11 12 >>>  0.1  + 0.1 0.2  >>>  0.2  + 0.2 0.4  >>>  2  * 0.1 0.2  >>>  2  * 0.2 0.4  >>>  0.2  + 0.1 0.30000000000000004  >>>  3  * 0.1 0.30000000000000004 
数据输入 基本语法 变量 = input()
input()的有趣之处在于,他的括号内部就相当于一个print()语句,但是这个自带的功能,会将输入的值视为字符串 ,需要自行进行强制转换 。
1 2 3 4 5 6 7 8 print ("请输入你的名字" )Name = input () ID = input ("请输入你的账号" ) Password = input ("请输入你的密码" ) Password = int (Password) ID_Again = int (input ("请再次确认你的密码" ))  
if语句 条件测试 和C/C++不同的是,python的if语句返回值为True/False,而并非1/0
检查是否相等 在Python中也是需要考虑大小写的
1 2 3 4 5 6 7 8 9 >>>car = 'bwm'  >>>car == 'bwm'  True >>>car = 'Bwm'  >>>car == 'bwm'  False >>>car = 'Bwm'  >>>car != 'Audi'   True 
当大小写无关紧要时,就可以搭配lower()或者upper()使用,来统一格式
比较数字 1 2 3 4 5 6 7 8 9 10 11 >>>  age = 18 >>>  age == 18 True >>>  age < 21 True  >>>  age <= 21 True  >>>  age > 21 False  >>>  age >= 21 False  
检查多个条件 可以使用and或者or来进行使用
二者逻辑为:
and 全真为真,一假全假
or    一真为真,全假为假
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 >>>  age_0 = 22  >>>  age_1 = 18  >>>  age_0 >= 21  and  age_1 >= 21  False  >>>  age_1 = 22  >>>  age_0 >= 21  and  age_1 >= 21  True >>>(age_0 >= 21 ) and  (age_1 >= 21 )  True >>>  age_0 = 22  >>>  age_1 = 18  >>>  age_0 >= 21  or  age_1 >= 21  True  >>>  age_0 = 18  >>>  age_0 >= 21  or  age_1 >= 21  False  
检查特定值 1 2 3 4 5 >>>  requested_toppings = ['mushrooms' , 'onions' , 'pineapple' ] >>>  'mushrooms'  in  requested_toppings True  >>>  'pepperoni'  in  requested_toppings False 
检查特定值不在列表中 可以使用关键字not in
1 2 3 4 banned_users = ['andrew' , 'carolina' , 'david' ]  user = 'marie'   if  user not  in  banned_users:     print (user.title() + ", you can post a response if you wish." )  
1 Marie, you can post a response if  you wish.  
具体语法 if语句 1 2 3 4 if  conditional_test:     do something           
1 2 3 4 age = 19   if  age >= 18 : 	print ("You are old enough to vote!" )   print ("Have you registered to vote yet?" )  
if-else语句 1 2 3 4 5 6 7 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!" )  
1 2 Sorry, you are too young to vote.  Please register to vote as  soon as  you turn 18 !  
if-elif-else语句 1 2 3 4 5 6 7 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." )  
1 Your admission cost is  $5.  
多个elif代码块 1 2 3 4 5 6 7 8 9 10 age = 12   if  age < 4 :    price = 0   elif  age < 18 :   price = 5   elif  age < 65 :    price = 10   else :    price = 5   print ("Your admission cost is $"  + str (price) + "." ) 
省略else代码块 在python中 即使使用了if-elif仍然可以不使用 else语句
not的使用 当if语句想要结果取反时也可以加入not关键字
not False == True
not True == False
注意事项 在使用if语句时,当其中一行满足条件时,完成其对应的代码块后,都会自动忽略,if语句中剩下的所有代码块。因此在只想执行一个代码块时,使用if-elif-else,而当要测试或运行多个代码块时,就是用多个if语句 
检查特殊元素 使用for循环来检查列表的特殊值
1 2 3 4 5 6 7 8 9 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 + "." )          print ("\nFinished making your pizza!" )
1 2 3 4 5 Adding mushrooms.  Sorry, we are out of green peppers right now.  Adding extra cheese.  Finished making your pizza!  
确定列表不是空的  在使用for循环前确定列表不为空时及其重要的
1 2 3 4 5 6 7 8 requested_toppings = []  if  requested_toppings: 	for  requested_topping in  requested_toppings:  		print ("Adding "  + requested_topping + "." )  	print ("\nFinished making your pizza!" )  else : 	print ("Are you sure you want a plain pizza?" )  
需要记住的是:在if语句中将列表名在条件表达式中时,元素在>=1时返回True,而为空时,返回False
使用多个列表 1 2 3 4 5 6 7 8 9 10 11 available_toppings = ['mushrooms' , 'olives' , 'green peppers' ,  'pepperoni' , 'pineapple' , 'extra cheese' ] requested_toppings = ['mushrooms' , 'french fries' , 'extra cheese' ] for  requested_topping in  requested_toppings:     if  requested_topping in  available_toppings:          print ("Adding "  + requested_topping + "." )      else :          print ("Sorry, we don't have "  + requested_topping + "." )  print ("\nFinished making your pizza!" ) 
1 2 3 4 5 Adding mushrooms.  Sorry, we don't have french fries.   Adding extra cheese.  Finished making your pizza! 
while循环 基本语法 1 2 3 4 while   条件:(bool 类型)	满足时,实现时间1      满足时,实现时间2      满足时,实现时间3   
PS:注意控制终止条件,避免出现死循环 
for循环 基本语法 1 2 for  临时变量 in  待处理数据集:    循环满足时执行的事件 
PS:与C/C++种不同的是,for循环处理的是数据集 ,而不是一段表达式,当数据集遍历结束后,for循环才会停止。
while与for循环的区别 
循环控制(自定义循环) 无限循环 适用场景  
 
while循环 :heavy_check_mark: 
:heavy_check_mark: 
任意循环场景 
 
for循环 :heavy_multiplication_x: 
:heavy_multiplication_x:(理论不可以) 
遍历数据容器等简单固定次数循环 
 
 
 
break和continue 使用方式与对象与C/C++完全一致,分别表示为跳出循环 和忽略本循环以下语句 
数据容器 为了方便查找,这次并没有把几个数据容器放在该标题之下
Python的数据容器是自由的,可以存储任何元素 ,无论是字符串,数字亦或是布尔类型,甚至可以是自己本身 ,而这个容器容纳的每一份数据称之为1个元素 
根据各个容器的特点不同,可以分为大致5类
是否支持重复元素 
是否可以进行修改 
是否有序 
 
 
列表(list) :heavy_check_mark: 
:heavy_check_mark: 
:heavy_check_mark: 
 
元组(tuple) :heavy_multiplication_x: 
 
字符串(str)  
集合(set)  
字典(dict)  
 
 
列表 Python的列表由[]来表示,用,来分隔其中的元素。这与C/C++的数组类似,并且列表的性质也与数组类似
1 2 3 >>>bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized' ]  >>>print (bicycles) ['trek' , 'cannondale' , 'redline' , 'specialized' ]  
访问列表元素 与数组一致,[0]表示首元素 
1 2 3 >>>bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized' ]  >>>print (bicycles[0 ]) trek 
而列表与众不同的是,其支持负数索引 ,通过索引为-1可以返回列表中的最后一个元素。
1 2 3 >>>bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized' ] >>>print (bicycles[-1 ])  specialized 
接下来把学过的知识remix 一下
1 2 3 4 >>>bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized' ]  >>>message = "My first bicycle was a "  + bicycles[0 ].title() + "."   >>>print (message) My first bicycle was a T  rek. 
列表嵌套列表 列表也是可以进行嵌套 的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 My_list = [[1 ,2 ],[3 ,4 ]] print (My_list[0 ])print (My_list[1 ])print (My_list[0 ][0 ])print (My_list[0 ][1 ])print (My_list[1 ][0 ])print (My_list[1 ][1 ])""" [1, 2] [3, 4] 1 2 3 4 """ 
当进行列表嵌套列表时,[x]是代表着第x个列表,而[x][y]代表着第x列表的第y个元素。而这第y个元素也可以是第
修改与删除元素 修改列表元素 可以通过赋值来直接永久性修改列表的某个值
1 2 3 4 5 6 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' ]  >>>print (motorcycles)  ['honda' , 'yamaha' , 'suzuki' ]  >>>motorcycles[0 ] = 'ducati'  >>>print (motorcycles)  ['ducati' , 'yamaha' , 'suzuki' ]  
列表添加元素 在列表末尾添加元素append() 基本用法
append(元素)
将指定的元素追加到列表的尾部 
1 2 3 4 5 6 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' ]  >>>print (motorcycles) ['honda' , 'yamaha' , 'suzuki' ]  >>>motorcycles.append('ducati' )  >>>print (motorcycles) ['honda' , 'yamaha' , 'suzuki' , 'ducati' ]  
列表插入元素insert() 基本用法
列表.insert(下标,元素)
在指定的下标位置,插入指定的元素 
1 2 3 4 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' ]  >>>motorcycles.insert(0 , 'ducati' )  >>>print (motorcycles) ['ducati' , 'honda' , 'yamaha' , 'suzuki' ]  
列表追加多个元素extend() 基本用法
列表.extend(其它数据容器)
将其它的数据容器的内容取出,依次追加到列表尾部
1 2 3 4 >>>my_list = [1 ,2 ,3 ] >>>my_list.extend([4 ,5 ,6 ]) >>>print (my_list) [1 ,2 ,3 ,4 ,5 ,6 ] 
从列表中删除元素 del语句 基本语法
del 列表[下标]
可以根据位置和值来删除列表中的元素
1 2 3 4 5 6 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' ]  >>>print (motorcycles)  ['honda' , 'yamaha' , 'suzuki' ]  >>>del  motorcycles[0 ]  >>>print (motorcycles)  ['yamaha' , 'suzuki' ]  
使用pop()删除元素 列表.pop(下标)
删除列表末尾的元素,并能够接着使用 
本质上就是 将这个元素从列表中移除,并作为返回值进行输出 
1 2 3 4 5 6 7 8 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' ]  >>>print (motorcycles)  ['honda' , 'yamaha' , 'suzuki' ]  >>>popped_motorcycle = motorcycles.pop()  >>>print (motorcycles)  ['honda' , 'yamaha' ] >>>print (popped_motorcycle)  suzuki 
popped_motorcycle作用:可以打印出最后一条消息
弹出列表中的任何位置处的元素 使用pop()并在()中指定删除的元素索引即可
1 2 3 4 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' ]  >>>first_owned = motorcycles.pop(0 )  >>>print ('The first motorcycle I owned was a '  + first_owned.title() + '.' )  The first motorcycle I owned was a Honda.  
PS:
当你想删除元素,并且不想使用时 ,使用del语句  
当你想删除元素,但是以后想使用时 ,使用pop()  
 
根据值删除元素remove() 1 2 3 4 5 6 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' , 'ducati' ]  >>>print (motorcycles) ['honda' , 'yamaha' , 'suzuki' , 'ducati' ] >>>motorcycles.remove('ducati' )  >>>print (motorcycles) ['honda' , 'yamaha' , 'suzuki' ] 
remove()从列表中删除元素时,也可接着使用它的值 
1 2 3 4 5 6 7 8 9 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' , 'ducati' ] >>>print (motorcycles)  ['honda' , 'yamaha' , 'suzuki' , 'ducati' ]  >>>too_expensive = 'ducati'   >>>motorcycles.remove(too_expensive)  >>>print (motorcycles)  ['honda' , 'yamaha' , 'suzuki' ]  >>>print ("\nA "  + too_expensive.title() + " is too expensive for me." )  A Ducati is  too expensive for  me.  
值得注意的是:使用的时候remove()只会删除第一个出现的元素,后续出现的重复元素不会删除。 
清空列表.clear() 基本语法
列表.clear()
清空列表内容
1 2 3 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' , 'ducati' ]  >>>motorcycles.clear() [] 
查询列表元素 基本语法 列表名称.index(元素)
功能:查找指定元素在列表的下标,找不到报错ValueError
1 2 3 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' , 'ducati' ]  >>>motorcycles.index("suzuki" ) 2 
index()就是变量这个函数中的方法 
没有学过C++面向对象思想的人,可能会问什么是方法呢? 
其实很简单,方法和函数本质是一样的,函数不过是散装在外面的,而方法是封装在一个类里的函数。 
同时使用方法也会有一些不同。 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 def  add1 (x, y ):    result = x + y     print (result) add1(1 , 2 ) class  Student :			    def  add2 (self,x, y ):         result = x + y         print (result) a=Student() a.add2(1 , 2 ) 
查询元素在列表中的数量 查询某元素的数量.count() 基本语法
列表.cont(元素)
可以查询某个元素在列表中的具体数量
1 2 3 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' , 'ducati' , 'ducati' ]  >>>motorcycles.cont('ducati' ) 2 
查询所有的元素数量len() 基本语法
len(列表)
可以查询列表中一共有多少个元素
1 2 3 >>>motorcycles = ['honda' , 'yamaha' , 'suzuki' , 'ducati' , 'ducati' ]  >>>len (motorcycles) 5 
组织列表 使用sort()对列表进行永久性的排序 1 2 3 4 5 >>>cars['bmw' ,'audi' ,'toyota' ,'subru' ] >>>cars.sort() >>>print (cars) ['audi' ,'bmw' ,'subaru' ,'toyota' ] 
如果想要以相反的方向输出可以选择使用reverse=True
1 2 3 4 5 >>>cars['bmw' ,'audi' ,'toyota' ,'subru' ] >>>cars.sort(reverse=True ) >>>print (cars) ['toyota' ,'subaru' ,'bmw' ,'audi' ] 
使用sorted()对列表进行临时性排序 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 cars = ['bmw' , 'audi' , 'toyota' , 'subaru' ]  >>>print ("Here is the original list:" )  >>>print (cars)  Here is  the original list :  ['bmw' , 'audi' , 'toyota' , 'subaru' ] >>>print ("\nHere is the sorted list:" )  >>>print (sorted (cars))  Here is  the sorted  list :  ['audi' , 'bmw' , 'subaru' , 'toyota' ]  >>>print ("\nHere is the original list again:" )  >>>print (cars)  Here is  the original list  again:  ['bmw' , 'audi' , 'toyota' , 'subaru' ] 
使用sorted()后,列表元素顺序并没有发生永久性改变 ,而是按照临时需求进行了改变,和上面说的一样,也可以通过传递reverse=True来反向输出
倒着打印列表reverse() 使用reverse()可以逆向输出一开始所设定的列表顺序。
1 2 3 4 5 6 >>>cars = ['bmw' , 'audi' , 'toyota' , 'subaru' ]  >>>print (cars)  >>>cars.reverse()  >>>print (cars)  ['bmw' , 'audi' , 'toyota' , 'subaru' ]  ['subaru' , 'toyota' , 'audi' , 'bmw' ]  
但是由于这种改变是永久性的 因此,可以通过再次调用reverse()来进行恢复顺序。
确定列表长度len() 1 2 3 >>>  cars = ['bmw' , 'audi' , 'toyota' , 'subaru' ]>>>  len (cars)4 
使用列表时避免索引错误 即与数组一直从0开始数数,所以是一定不要超过n-1个数的调用。但python有趣的地方在于,可以使用负数索引即-1就是倒数第一个元素
PS:当出现索引错误而不知所措时,可以通过len()来确定列表长度
操作列表 while循环遍历列表 1 2 3 4 5 6 7 def  list_while_func 	magicians = ['alice' , 'david' , 'carolina' ]      index = 0      while  index<len (magicians):     element = magicians[index]     print (f"列表的元素:{element} " )     index +=1  
for循环遍历列表 当想要进行遍历列表时,可以选择使用for循环,值得注意的是,python的for循环与C/C++的并不相同
1 2 3 4 5 magicians = ['alice' , 'david' , 'carolina' ]  for  magician in  magicians:           	print (magician)  
for循环代码风格小贴士 1 2 3 for cat in cats:  for dog in dogs:  for item in list_of_items: 
在for循环中执行更多操作 当for循环的缩进下没有语句时会自动停止for循环
1 2 3 4 magicians = ['alice' , 'david' , 'carolina' ] for  magician in  magicians:print (magician.title() + ", that was a great trick!" )print ("I can't wait to see your next trick, "  + magician.title() + ".\n" ) 
1 2 3 4 5 6 7 8 Alice, that was a great trick!  I can't wait to see your next trick, Alice.   David, that was a great trick!  I can' t wait to see your next  trick, David. Carolina, that was a great trick!  I can't wait to see your next trick, Carolina.   
避免缩进错误 Python中的缩进 所及是极其重要的,就如同C/C++中的括号,它们是用来判断代码与前一行代码之间的关系 
忘记缩进 1 2 3 magicians = ['alice' , 'david' , 'carolina' ]  for  magician in  magicians: print (magician) 
1 2 3 4 File "magicians.py" , line 3   	print (magician)  		 ^  IndentationError: expected an indented block 
通常出现这种错误可以将紧跟在for语句后的代码进行缩进,就可消除这种缩进错误。
不必要的缩进 当你多输入了一个缩进时,python会进行如下报错
1 2 message = "Hello Python world!"   	print (message) 
1 2 3 4 File "hello_world.py" , line 2   	print (message)  	^  IndentationError: unexpected indent 
创建数值列表 使用range() 1 2 for  value in  range (1 ,5 )	print (value) 
会发现并没有5,这是就是编程中经常出现的差一行为 ,因为Python是在第一个值开始数,当达到你指定的第N个值后停止,因此不包含第N个值
因此当输出结果不符合预期时,可以进行±1 
range()可以和list()进行搭配使用
1 2 numbers = list (range (1 ,6 ))  print (numbers) 
同时 range()还可以指定打印出步长step,例如打印1~10的偶数
1 2 even_number = list (range (2 ,11 ,2 ))  print (even_number)
使用range()几乎能够创建任何需要的数字集,例如我们需要一个1~10的平方
1 2 3 4 5 squares = []  for  value in  range (1 ,11 ): 	squares.append(value**2 )       print (squares) 
1 [1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 ]  
对数字列表执行简单的统计计算 1 2 3 4 5 6 7 >>>digits = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,0 ] >>>min (digits) 0 >>>max (digits) 9 >>>sum (digits) 45 
列表解析 1 2 3 squares = [value**2  for  value in  range (1 ,11 )]  print (squares) 
1 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]  
切片 值得注意的是,这里的索引可以通过:的方式
1 2 players = ['charles' , 'martina' , 'michael' , 'florence' , 'eli' ]  print (players[0 :3 ]) 
1 ['charles' , 'martina' , 'michael' ]  
这个和之前提到的range()的数数一致,x:N==x~N-1
而当没有第一个索引即:N则自动从列表开头开始 即0~N-1
同时当美哟最后一个索引时即x:会自动从N开始知道末尾即x~N
而且这种索引也支持使用负数
1 2 3 4 5 6 7 8 9 10 11 >>>players = ['charles' , 'martina' , 'michael' , 'florence' , 'eli' ] >>>print (players[0 :3 ]) ['charles' , 'martina' , 'michael' ]  >>>print (players[1 :4 ])  ['martina' , 'michael' , 'florence' ]  >>>print (players[:4 ])  ['charles' , 'martina' , 'michael' , 'florence' ]  >>>print (players[2 :])  ['michael' , 'florence' , 'eli' ] print (players[-3 :]) ['michael' , 'florence' , 'eli' ] 
遍历切片
加入要遍历前三个人 就可以使用for循环 进行遍历
1 2 3 players = ['charles' , 'martina' , 'michael' , 'florence' , 'eli' ] for  player in  players[:3 ]:     print (player.title())  
1 2 3 Charles  Martina  Michael  
复制列表 可以使用[:]这样可以让python创建一个始于第一个元素,终止于最后一个元素的切片。
1 2 3 4 5 6 7 8 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) 
1 2 3 4 My favorite foods are:  ['pizza' , 'falafel' , 'carrot cake' ]  My friend's favorite foods are:   [' pizza', ' falafel', ' carrot cake'] 
这样得到的是两个不同的列表
而直接通过赋值,不加[:]不过是一个列表但是有两个名称罢了
1 2 3 4 5 6 7 8 9 10 11 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)
1 2 3 4 5 My favorite foods are:  ['pizza' , 'falafel' , 'carrot cake' , 'cannoli' , 'ice cream' ]  My friend's favorite foods are:   [' pizza', ' falafel', ' carrot cake', ' cannoli', ' ice cream'] 
因此事实证明直接 以=相连是同一个列表,而加上[:]才是真正的又 创建了一个,一摸一样的列表
元组 元组即不可变的列表 
创建元组 1 2 3 4 dimensions = (200.50 ) dimensions = tuple (200.50 ) print (dimensions[0 ])print (dimensions[1 ])
当然吐过想尝试修改元组的元素,当然是被禁止,且会报错的
遍历元组 遍历元组的方式与遍历列表的方式一致
1 2 3 dimensions = (200.50 ) for  dimension in  dimensions	print (dimension) 
修改元组变量 就如上所说,修改元组变量是不可行的,但是我们可以给代表这个元组的变量,重新赋值。
说人话就是“解决不了问题,就解决发现问题的人”
从根本上把元组覆盖就可以了
1 2 3 4 5 6 7 8 9 dimensions = (200 , 50 ) print ("Original dimensions:" ) for  dimension in  dimensions: 	print (dimension)       dimensions = (400 , 100 )  print ("\nModified dimensions:" ) for  dimension in  dimensions: 	print (dimension)  
1 2 3 4 5 6 7 Original dimensions:  200  50  Modified dimensions:  400  100 
字典 创建字典 1 2 3 4 alien_0 = {'color' : 'green' , 'points' : 5 }  print (alien_0['color' ]) print (alien_0['points' ]) 
使用字典 python的字典,就是一系列的键-值对
格式:字典名称 = {'键':'值'}
访问字典的值 1 2 alien_0 = {'color' : 'green' }  print (alien_0['color' ]) 
添加键-值对 可以通过字典名称['键']=值来直接创建
1 2 3 4 5 alien_0 = {'color' : 'green' , 'points' : 5 }  print (alien_0) alien_0['x_position' ] = 0   alien_0['y_position' ] = 25   print (alien_0)
1 2 {'color' : 'green' , 'points' : 5 }  {'color' : 'green' , 'points' : 5 , 'y_position' : 25 , 'x_position' : 0 }  
修改字典中的值 修改字典的值可以直接进行修改
1 2 3 4 alien_0 = {'color' : 'green' }  print ("The alien is "  + alien_0['color' ] + "." ) alien_0['color' ] = 'yellow'   print ("The alien is now "  + alien_0['color' ] + "." ) 
1 2 The alien is  green.  The alien is  now yellow.  
删除键-值对 可以使用del语句将对应键值对删除,删除时必须指明所需要删除的键与字典名
1 2 3 4 5 alien_0 = {'color' : 'green' , 'points' : 5 }  print (alien_0) del  alien_0['points' ] print (alien_0) 
1 2 {'color' : 'green' , 'points' : 5 }  {'color' : 'green' }  
创建字典小提示 当遇到大量类似对象时,可以选择使用换行缩进 的方式,进行赋值,从而提高可读性
1 2 3 4 5 6 favorite_languages = {  	'jen' : 'python' ,  	'sarah' : 'c' ,  	'edward' : 'ruby' ,  	'phil' : 'python' ,   }  
遍历字典 遍历所有的键-值对 同样与其他遍历一样,可以利用for循环来遍历
1 2 3 4 5 6 7 8 user_0 = {  	'username' : 'efermi' ,  	'first' : 'enrico' ,  	'last' : 'fermi' ,   }  for  key, value in  user_0.items(): 	print ("\nKey: "  + key)  	print ("Value: "  + value)  
1 2 3 4 5 6 7 8 Key: last  Value: fermi  Key: first  Value: enrico  Key: username  Value: efermi  
会发现,输出顺序 与设定顺序并不一致 ,因为Python并不关心 键-值对存储的顺序,仅仅是跟踪键和值的关联关系 
遍历字典中的所有键 可以使用key()来进行遍历所有键
1 2 3 4 5 6 7 8 9 10 favorite_languages = {  	'jen' : 'python' ,  	'sarah' : 'c' ,  	'edward' : 'ruby' ,  	'phil' : 'python' ,   }  for  name in  favorite_languages.keys():    print (name.title()) for  name in  favorite_languages:    print (name.title()) 
1 2 3 4 5 6 7 8 9 Jen  Sarah  Phil  Edward  Jen  Sarah  Phil  Edward  
而我们即使不用Keys()也可以进行遍历所有的键,因为Python在遍历字典是默认遍历所有的键
我们也可以按照顺序 遍历字典中的所有键,可以使用sorted()来按特定顺序进行排列
1 2 3 4 5 6 7 8 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." )  
1 2 3 4 Edward, thank you for  taking the poll.  Jen, thank you for  taking the poll.  Phil, thank you for  taking the poll.  Sarah, thank you for  taking the poll.  
遍历字典中的所有值 遍历字典中的所有值可以利用方法values()
1 2 3 4 5 6 7 8 favorite_languages = {  	'jen' : 'python' ,  	'sarah' : 'c' ,  	'edward' : 'ruby' ,  	'phil' : 'python' ,   }  for  language in  favorite_languages.values(): 	print (language.title())  
而当我们只想要具体的种类,需要去重时 ,可以使用集合set()
1 2 3 4 5 6 7 8 favorite_languages = {  	'jen' : 'python' ,  	'sarah' : 'c' ,  	'edward' : 'ruby' ,  	'phil' : 'python' ,   }  for  language in  set (favorite_languages.values()): 	print (language.title())  
嵌套(俄罗斯套娃) 即列表套字典,字典套列表,字典套字典。
本质上很简单,只需要注意调用字典内容时要主意好对应键就可以了 
列表存字典 1 2 3 4 5 6 7 8 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)  
1 2 3 {'color' : 'green' , 'points' : 5 }  {'color' : 'yellow' , 'points' : 10 }  {'color' : 'red' , 'points' : 15 }  
字典存列表 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 You ordered a thick-crust pizza with  the following toppings:  	mushrooms  	extra cheese 
字典存字典 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())  
1 2 3 4 5 6 Username: aeinstein   	Full name: Albert Einstein   	Location: Princeton  Username: mcurie   	Full name: Marie Curie   	Location: Paris  
函数 函数的意义 函数的意义很显然就是为了增加代码的复用率,减少写重复代码的麻烦
自定义函数的基础语法 1 2 3 4 5 def  自定义函数名称  (传入参数):	执行的语句     return  返回值 def  hello ():	print ("Hello World" ) 
和C/C++不同的是,Python的自定义函数不用给函数的返回值设定函数类型,因此在Python中,返回值是可以忽略不写的 
甚至可以不传参 ,直接执行里面的语句
同C/C++一样,在开始深入函数之前,不妨来实现以下len()(求字符串长度)的函数
1 2 3 4 5 6 7 8 9 def  my_len (str_ ):    cont = 0      for  i in  str_:         cont += 1      print (f"{str_} 的个数为{cont} 个" ) str1 = "asd4as56d4as65"  str2 = "asd4a5654655"  my_len(str1) my_len(str2) 
函数的传入参数 1 2 3 def  自定义函数名称  (传入参数):	执行的语句     return  返回值 
在Python的函数中,实参和形参使用的方式是一样的
调用函数时,使用的是实际参数(实参)
函数定义中,使用的是形式参数(形参)
函数的返回值 Python函数的返回值极其简单,就是根据最后的结果,来判断返回值的数据类型
None类型 Python定义函数时,如果没有return语句,那么函数有返回值吗?
答案是:有的 
Python中有一个特殊的量:None,它的类型是<class 'NoneType'>
因此当没有返回值 的时候,实际是返回了None(即空的,无实际意义)
应用场景 1.函数无返回值时 就如刚才说的那样
2.if判断 None等同于False
一般用于函数中主动返回None去和if判断打配合
3.声明无内容的变量 当变量暂时不需要有具体值时,可以用None来代替
函数的嵌套 对于C/C++有一定基础的话,对这个想必一定不陌生
所谓的嵌套使用,就是在一个函数中又去使用了另外一个函数
1 2 3 4 5 6 7 def  fun_b ():    print ("2" ) def  fun_a ():    print ("1" )     fun_b()     print ("1" ) fun_a() 
函数的变量作用域  变量作用域指的是变量的作用范围,也是分为两类(局部变量和全局变量)
局部变量 只能 在函数体 内使用的变量
1 2 3 4 5 6 def  test_a ():	num = 100      print (num)      test_a() print (num)
全局变量 函数体内外 都可以使用的变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 num = 100  def  test_a ():    print (num)      def  test_b ():    num=500      print (num) test_a() test_b() print (num)""" 100 500 100 """ 
在Python中如果函数体修改了全局变量的值,那么这个全局变量就会变成局部变量 ,因此函数体内修改全局变量,只会在函数体内发生改变 不会对函数体外产生改变
那么我想要在函数体内修改全局变量呢?
这时候就可以引出我们的global
global 关键字 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 num = 100  def  test_a ():    print (num)      def  test_b ():    global  num     num=500      print (num) test_a() test_b() print (num)""" 100 500 500 """ 
函数的说明文档 为什么要给说明文档单起一个大标题呢?
原因跟简单,说明文档十分的重要,为了以后的自己和工作后接手的同事不去骂现在的自己,在书写函数时,在函数里,加一些注释时很有必要的,接下来就是函数注释时需要提及的东西。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def  add  (x,y):	     """  	add 函数 可以接收两个参数,进行两个参数相加的功能 	:param x:形参x表示相加的其中一个数字 	:param y:形参y表示相加的另外一个数字 	:return:返回值为x 与 y 相加的结果 	"""          """      其中      :param:用于解释参数     :return:返回值的说明     """     result = x+y     return  result 
因此不难看出,重点需要写的东西就是 函数实现的功能  调用的参数意义  和 返回值表达的意思