Python基础语法 
输出 
1 2 3 4 print('helloworld' ) print('I am' ,'chenshilin' ) print('100+200=' ,100 +200 ) 
 
 
输入 
1 2 3 name = input () name = input ('please enter a integer:' ) 
 
转义字符 
转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\
Python还允许用r''表示''内部的字符串默认不转义
1 2 print(r'''hello,\n  world''' )
 
hello,\n 
world
1 2 print('''hello,\n  world''' )
 
hello,
world
布尔 
可以直接使用True和False (严格区分大小写) 
可以使用and, or, not运算
变量 
Python语言的变量定义为动态语言,不用定义变量类型
1 2 3 4 5 6 a = 100  t_007 = 'T007'  Answer = True  
 
列表:list 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 classmates = ['Michael' , 'Bob' , 'Tracy' ] classmates[0 ] len (classmates)classmates.append('Adam' ) classmates.insert(1 , 'Jack' ) classmates.pop() pop_bob = classmates.pop(1 ) del  classmates[0 ]classmates.remove('Bob' ) L = ['Apple' , 123 , True ] 
 
切片 
1.列表切片在作为参数传递给函数时,表明传递的是一个副本,并不是本身
在这种情况下,如若函数对其更改,将不会改变其原有的值
2.切片的另一主要的用途为,顾名思义,对列表进行分割
元组:tuple 
tuple一经初始化就不能修改
1 2 3 4 5 classmates = ('Michael' , 'Bob' , 'Tracy' ) t = (1 ,) t = (1 ) 
 
条件判断 
1 2 3 4 5 6 7 age = 3  if  age >= 18 :    print('adult' ) elif  age >= 6 :    print('teenager' ) else :    print('kid' ) 
 
注意不要少写了冒号:,缩进通常为4格
if语句执行有个特点,它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elif和`else
类似C语言中的switch/case语句
1 2 3 4 5 6 7 8 s = input ('birth: ' ) birth = int (s) if  birth < 2000 :    print('00前' ) else :    print('00后' )      
 
循环 
1 2 3 4 5 sum  = 0 for  x in  range (101 ):    sum  = sum  + x print(sum ) 
 
for x in …循环就是把每个元素代入变量x,然后执行缩进块的语句
1 2 3 4 5 6 7 sum  = 0 n = 99  while  n > 0 :    sum  = sum  + n     n = n - 2  print(sum ) 
 
dict 和 set 
字典:dict 
即map,使用键-值(key-value)存储,具有极快的查找速度
1 2 3 4 5 6 7 8 9 10 11 names = ['Michael' , 'Bob' , 'Tracy' ] scores = [95 , 75 , 85 ] d = {'Michael' : 95 , 'Bob' : 75 , 'Tracy' : 85 } d['Michael' ] d['Adam' ] = 67  d['Michael' ] = 100  d.pop('Bob' ) 
 
判断key的存在,有两种办法,一是通过in判断key是否存在:
 
二是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
1 2 d.get('Thomas') d.get('Thomas',-1) 
 
1 2 3 for  key, value in  d.items():    print(key+':' +value) 
 
set 
不允许有重复的值
1 2 3 >>>  s = set ([1 , 1 , 2 , 2 , 3 , 3 ])>>>  s{1 , 2 , 3 } 
 
传入的参数[1, 1, 2, 2, 3, 3]是一个list
 
set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:
1 2 3 4 5 6 >>>  s1 = set ([1 , 2 , 3 ])>>>  s2 = set ([2 , 3 , 4 ])>>>  s1 & s2{2 , 3 } >>>  s1 | s2{1 , 2 , 3 , 4 } 
 
何谓不可变 
1 2 3 4 5 6 7 >>>  a = 'abc' >>>  b = a.replace('a' , 'A' )>>>  b'Abc' >>>  a'abc' 
 
函数 
1 2 3 4 5 6 def  my_abs (x ):    if  x >= 0 :         return  x     else :         return  -x 
 
def函数时,需要确定函数名和参数个数;
如果有必要,可以先对参数的数据类型做检查;
函数体内部可以用return随时返回函数结果;
函数执行完毕也没有return语句时,自动return None。
函数可以同时返回多个值,但其实就是一个元组tuple
函数的参数 
位置参数 
1 2 3 4 5 6 def  power (x, n ):    s = 1      while  n > 0 :         n = n - 1          s = s * x     return  s 
 
x,n就被称为位置参数
默认参数 
1 2 3 4 5 6 def  power (x, n=2  ):    s = 1      while  n > 0 :         n = n - 1          s = s * x     return  s 
 
n为默认参数
可变参数 
可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个
1 2 3 4 5 6 7 8 9 10 11 def  calc (numbers ):    sum  = 0      for  n in  numbers:         sum  = sum  + n * n     return  sum  calc([1 ,2 ,3 ]) calc((1 ,2 ,3 ,4 )) calc(1 ,2 ,3 ) 
 
1 2 3 4 5 def  calc (*numbers ):    sum  = 0      for  n in  numbers:         sum  = sum  + n * n     return  sum  
 
定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:
命名关键字参数 
对于关键字参数,函数的调用者可以传入任意不受限制的关键字参数。
 
关键字参数 
1 2 3 4 5 6 7 8 def  person (name, age, **kw ):    print('name:' , name, 'age:' , age, 'other:' , kw)           >>>  person('Bob' , 35 , city='Beijing' )name: Bob age: 35  other: {'city' : 'Beijing' } >>>  person('Adam' , 45 , gender='M' , job='Engineer' )name: Adam age: 45  other: {'gender' : 'M' , 'job' : 'Engineer' } 
 
也可以将dict字典传入
1 2 3 4 5 6 7 >>>  extra = {'city' : 'Beijing' , 'job' : 'Engineer' }>>>  person('Jack' , 24 , city=extra['city' ], job=extra['job' ])name: Jack age: 24  other: {'city' : 'Beijing' , 'job' : 'Engineer' } >>>  person('Jack' , 24 , **extra)name: Jack age: 24  other: {'city' : 'Beijing' , 'job' : 'Engineer' } 
 
类 
封装 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class  Dog ():    """小狗类"""      def  __init__ (self, name, age ):         self.name = name         self.age = age     def  sit (self ):         print(self.name.title() + " is now sitting" )     def  roll_over (self ):         print(self.name.title() + " rolled over!" ) 
 
创建类时,使用构造函数时要使用两个_
继承 
1 2 3 class  ElectricCar (Car ):    def  __init__ (self, make, model, year ):         super ().__init__(self, make, model, year) 
 
super()是一个特殊的函数,帮助python将子类和父类关联起来。父类因为被称为超类,super因此而得名
文件读取 
方法一:遍历逐行读取 
1 2 3 4 5 filename  = 'pi_digits.txt'  with  open (filename) as  file_project:    for  line in  file_project:         print(line) 
 
方法二:读取整个文件 
1 2 3 with open('pi_digits.txt') as file_project:     contents = file_project.read()     print(contents) 
 
方法三:写到一个列表中 
1 2 3 4 5 6 7 filename  = 'pi_digits.txt'  with  open (filename) as  file_project:    lines = file_project.readlines()      for  line in  lines:    print(line) 
 
文件写入 
写入空文件 
1 2 3 4 filename = 'programming.txt'  with  open (filename, 'w' ) as  file_project:    file_project.write('i love programming' ) 
 
读取模式’r’, 写入模式’w’, 附加模式’a’
异常 
1 2 3 4 try :    print(5 /0 ) except  ZeroDivisionError:    print("You can't divide by zero!" ) 
 
try-except-else 
只有会出现异常的代码块才需要放在try当中,如果程序出现了意料之中的异常提醒,那么会执行except中的代码;如果运行正常,会接着执行else中的代码
异常类型包括:
ZeroDivisionError
FileNotFoundErrot
存储数据 json 
写入 
1 2 3 4 5 6 import  jsonnumbers = [2 , 3 , 5 , 7 , 11 , 13 ] filename = 'numbers.json'  with  open (filename, 'w' ) as  f_obj:    json.dump(numbers, f_obj) 
 
读出 
1 2 3 4 5 6 7 import  jsonfilename = 'numbers.json'  with  open (filename) as  f_obj:    numbers = json.load(f_obj) print(numbers) 
 
重构 
将代码划分为一系列完成具体工作的函数
测试 
单元测试函数 
1 2 3 4 5 6 7 8 9 10 11 12 13 import  unittestfrom  name_function import  get_formatted_nameclass  NamesTestCase (unittest.TestCase ):    def  test_first_last_name (self ):         formatted_name = get_formatted_name('janis' , 'joplin' )                  self.assertEqual(formatted_name, 'Janis Joplin' )          unittest.main() 
 

测试类,方法setUp() 
setUp()方法创建一系列实例,就可以避免在每个测试方法中再创建
survey.py 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class  AnonymousSurvey ():    """创建一个匿名调查类"""      def  __init__ (self, question ):         """初始化一个问题"""          self.question = question         self.responses = []     def  show_question (self ):         """显示调查问卷"""          print(self.question)     def  store_response (self, new_response ):         """存储新的回答"""          self.responses.append(new_response)     def  show_results (self ):         """显示收集到的所有回答"""          print("Survey results:" )         for  response in  self.responses:             print('-'  + response) 
 
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 import  unittestfrom  survey import  AnonymousSurveyclass  TestAnonymousSurvey (unittest.TestCase ):    """针对AnonymousSurvey类的测试"""      def  setUp (self ) -> None :         """          创建一个调查对象和一组答案,供后续测试使用         """         question = "What language did you first learn to speak?"          self.my_survey = AnonymousSurvey(question)         self.responses = ['English' , 'Spanish' , 'Mandarin' ]         def  test_store_single_response (self ):             self.my_survey.store_reponse(self.response[0 ])             self.assertIn(self.response[0 ], self.my_survey.responses)         def  test_store_three_response (self ):             for  response in  self.responses:                 self.my_survey.store_reponse(response)             for  response in  self.responses:                 self.assertIn(response, self.my_survey.responses) unittest.main() 
 
参考文献 
1.《Python编程:从入门到实践》美Eric Matthes著
2.https://www.liaoxuefeng.com/