快速过一遍 Python
Python 之禅 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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! '''
Python 命名规范 传送门
基本数据类型 定义:
1 2 message = "Hello Python!" print (message)
字符串 可以是单引号 ' '
,也可以是双引号 " "
,之间可以相互嵌套。
API
Document:
1 2 3 4 5 6 name = "Gulf Alaska" name.tile() name.upper() name.lower() name.lstrip() name.rstrip()
切片 不仅列表有切片,字符串也有:
1 2 3 4 5 print (name[0 ]) print (name[1 ]) print (name[2 ]) print (name[2 :7 ])
数字 1 2 3 4 5 6 7 8 print (3 / 2 ) print (3 ** 3 ) print (3 // 2 ) ''' python数字类型不会自动转string类型, 需要str()支撑 ''' print ("Hello: " + str (143 ))
列表 Python 中,用方括号 []
表示列表,并用逗号来分隔其中的元素。
1 2 3 4 5 lista = ['hi' , 'Fighting' , 'hhh' ] print (lista) print (lista[1 ]) print (lista[-1 ])
修改元素 1 2 3 4 5 6 lista[0 ] = 'hello' lista[-1 ] = 'hello' lista[-2 ] = 'hello'
添加元素 1 2 lista.append('what' ) lista.insert(1 , 'hihihi' )
删除元素 1 2 3 4 del lista[0 ]member = lista.pop() member = lista.pop(3 ) lista.remove('hi' )
排序列表 1 2 3 4 5 6 numberList.sort() numberList.sort(reverse=True ) sorted (numberList)sorted (numberList, reverse=True )numberList.reverse() len (numberList)
遍历列表 Python 根据缩进 来判断代码行与前一个代码行的关系 !
随意缩进会导致错误!
1 2 3 4 for x in list : print (x) print (x + str (666 ))
数值列表 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 for i in range (1 , 5 ): print (i) for i in range (30 ): print (i) number = list (range (1 , 6 )) print (number)for i in range (1 , 11 , 2 ): print (i) print (min (number))print (max (number))print (sum (number))x2 = [] for x in range (1 , 11 ): x2.append(x ** 2 ) print (x2)square = [value ** 2 for value in range (1 , 11 )] print (square)
切片 切片:即使用列表的一部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 techs = ['vue' , 'react' , 'spring' , 'spring boot' , 'spring cloud' , 'java' , 'javascript' , 'python' , 'c' , 'c++' , 'go' ] print (techs[1 :3 ])print (techs[2 :])print (techs[:4 ])print (techs[:])for i in techs[2 :6 ]: print (i) myStack = techs[:] print ("myStack: " + str (myStack))yours = techs techs.append("is?!" ) print (techs)print (yours)
列表的其他操作 1 2 3 4 5 6 7 8 9 10 11 print ('hi' in _list ) print ('hi' not in _list ) request = [] if request: print ('not null' ) else : print ('null' )
元组 元组:即不可变 (不可修改)的列表
1 2 3 4 5 6 7 8 list = [1 , 2 , 3 ]dimensions = (1 , 2 , 3 ) for dimension in dimensions: print (dimension) dimensions = (2 , 3 , 4 )
相对于列表,元组是更简单的数据结构。如果需要存储的一组值在整个生命周期内都不变,可使用元组。
for 循环、if 条件判断 for 循环在前文其实已经谈到了,不清楚的可以回看一下。
注意:for
、if
、else
这种都不需要括号 ()
,但都需要冒号 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 nums = [1 , 3 , 4 , 6 , 7 , 9 , 14 ] for num in nums: if num <= 6 : print ('small' ) elif 6 < num < 10 : print ('middle' ) else : print ('big' ) if 6 in nums: print ('好耶!' ) print (10 in nums)print (10 not in nums)
布尔表达式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 if 6 in nums: print ('好耶!' ) print (10 in nums) print (10 not in nums) request = [] if request: print ('not null' ) else : print ('null' ) if i > 6 and j < 3 : print ('and' ) elif i < 3 or j >= 6 : print ('or' )
字典 在 Python 中,字典是一系列 ‘键值对 ‘,好比 Java 中的 Map 数据结构。
1 2 3 4 languages = {'TypeScript' : 'not' , 'Java' : 'good' , 'C++' : 'Not Good' , 'C' : 'just so so' , 'Python' : 'Learning' , 'Go' : 'hurry' } print (languages['TypeScript' ]) print (languages['Go' ])
访问 1 print (languages['Python' ])
添加 1 2 languages['Kotlin' ] = 'Android Language'
修改 1 2 languages['Go' ] = 'nearly'
删除
遍历字典 1 2 3 4 5 6 for lang, level in languages.items(): print (lang + ': ' + level) for keyValue in languages.items(): print (keyValue)
遍历字典中的所有键 1 2 3 4 5 6 7 for key in languages.keys(): print (key.title()) for key in sorted (languages.keys()): print (key.title())
遍历字典中的所有值 字典的键是默认不重复的,那如果想要值也不重复,那么就需要用到 set()
来找出独一无二的元素。
1 2 3 4 5 6 7 for value in languages.values(): print (value.upper()) for value in set (languages.values()): print (value)
嵌套 字典嵌套列表;列表嵌套字典;字典嵌套字典;列表嵌套列表。无异于 JavaScript。
字典列表
列表中存储字典
1 2 3 4 5 6 7 obj1 = {'key1' : 'val1' } obj2 = {'key2' : 'val2' } obj3 = {'key3' : 'val3' } objList = [obj1, obj2, obj3] for obj in objList: print (obj)
字典中存储列表 1 2 3 4 5 6 7 8 9 10 11 12 13 pizza = { 'crust' : ['thick' , 'think' ], 'toppings' : ['mushrooms' , 'extra cheese' ] } for key, value in pizza.items(): print ('key: ' + key) for topping in value: print ('value: ' + topping) for topping in pizza['toppings' ]: print (topping)
字典中存储字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 users = { 'user1' : { 'name' : 'hi' , 'age' : 19 }, 'user2' : { 'name' : 'hello' , 'age' : 20 }, 'user3' : { 'name' : 'halo' , 'age' : 21 }, } for username, info in users.items(): print (username + ": " + str (info))
列表中存储列表 1 2 3 4 5 6 7 infoList = [ [1 , 2 , 3 ], ['a' , 'b' , 'c' ] ] for info in infoList: print (info)
Remember
if、elif、else、while 都需要冒号 !
包括后面要学的函数定义,也是如此!
⭐因为 Python 中 :
等价于 {}
1 2 3 4 5 6 while True : phone = input ('please input your telephoneNumber: ' ) if phone == 'q' : break print (phone)
使用 int()
获取数值输入 1 2 3 4 5 6 7 8 while True : ids = input ('please input your ID: ' ) if ids == 'q' : break ids = int (ids) if ids >= 143 : print (ids)
函数 基本定义与使用 :
1 2 3 4 5 def add_two_number (message ): print (message) add_two_number('Hello Python!' )
传递参数 位置实参 1 2 3 4 5 def function1 (name, age ): print (name + ': ' + str (age)) function1('alawan' , 23 )
关键词实参 1 2 3 4 5 def function1 (name, age ): print (name + ': ' + str (age)) function1(age=26 , name='hhh' )
默认值 使用默认值时,在形参列表中必须先列出没有默认值的参数,再列出有默认值的参数。
1 2 3 4 5 6 7 def function2 (age, name='Judge' ): print (name + ": " + str (age)) function2(16 ) function2(16 , 'notDefault' )
返回值 1 2 3 4 5 6 7 8 9 10 def function3 (message ): return message msg = function3('GG' ) msg = function3({'name' : 'p' , 'age' : 19 }) msg = function3([1 , 2 , 3 ])
传递列表
传递 参数中存在一个比较特殊的情况,也就是形参是列表:
普通传入的话,函数是可以修改列表的,也就是和列表共用一个引用对象
还有一种的禁止函数修改列表 方式的传入
但不论怎么传入函数的,函数的定义还是一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 def greet_users (users ): for user in users: print ('hello: ' + user) _users = ['qqq' , 'www' , 'eee' , 'rrr' , 'ttt' ] greet_users(_users[:]) print (_users)greet_users(_users) print (_users)
传递任意数量的实参 结合使用位置实参和任意数量实参 1 2 3 4 5 6 7 8 9 10 11 def any_args_function (*langs ): for lang in langs: print (lang, end='\t' ) any_args_function(['Go' , 'Java' , 'C' , 'C++' , 'Python' , 'PHP' , 'TypeScript' ], {'name' : 'q' , 'age' : 19 }) any_args_function('Go' , 'Python' , 'C++' , 'C' )
使用任意数量的关键字实参 1 2 3 4 5 6 7 8 9 10 def build_profile (first, last, **user_info ): profile = {'first_name' : first, 'last_name' : last} for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('Gulf' , 'Alaska' , key1='value1' , key2='value2' ) print (user_profile)
模块 import
语句允许在当前运行的程序文件中使用模块中的代码。
1 2 3 4 import packaeg_name.module_namemodule_name.function1()
1 2 3 4 5 from packaeg_name.module_name import function1, function2flag = function1() area = function2()
1 2 3 from packaeg_name.module_name import function1 as fnfn()
1 2 3 import packaeg_name.module_name as _module_module.function1()
1 2 3 4 from modules_name import *function1() function2()
类 类中的实例函数形参都需要 self
变量 !
定义和使用类 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 class iPhone : def __init__ (self, id , number, date ): self .id = id self .number = number self .date = date def ringing (self ): print ('Your iphone is ringing!' ) def hang_on (self ): print ('Hang on your phone..' ) class Person : """构造函数""" def __init__ (self, name, age, sex ): self .name = name self .age = age self .sex = sex self .my_iPhone = iPhone(1 , 1183859291 , '2022-03' ) def say_hello (self, other_name ): print (self .name + ': Hello, ' + other_name) self .my_iPhone.ringing() self .my_iPhone.hang_on() person = Person('Gulf of Alaska' , 19 , 'F' ) person.say_hello('someone' ) print (person) print (person.name)print (person.sex)print (person.age)
继承 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 class Phone : """构造函数""" def __init__ (self, id , number, date ): self .id = id self .number = number self .date = date def ringing (self ): print (self .id + self .number) print ('Your phone is ringing!' ) def hang_on (self ): print (self .date) print ('Hang on your phone..' ) class HuaWei (Phone ): def __init__ (self ): """先初始化父类 (因为初始化父类后, 父类才能有属性, 子类才能继承)!!!""" super (HuaWei, self ).__init__(1 , 119 , 'now' ) print ('__init__' ) def xiao_yi (self ): print ('这里是小艺, 有什么能帮助你的吗?' ) wd = HuaWei() wd.ringing() wd.hang_on() wd.xiao_yi()
导入类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from main import Mathmath = Math(2 , 3 ) math.two_sum() from main import Math, Timeimport mainmyMath = main.Math(2 ,3 ) myMath.two_sum() from main import *Math(1 , 2 ).two_sum()
文件和异常 文件读取
open()
返回一个文件对象,需要提供实参文件路径
read()
读取文件全部内容
readline()
读取单行
readlines()
读取文件的每一行,然后返回一个列表
文件路径:Windows 使用反斜杠(\)而不是 Linux/OS X 的斜杠(/)
1 2 3 4 with open ('pi_digits.txt' ) as file_object: contents = file_object.read() print (contents)
1 2 3 4 5 6 7 8 9 filename = "my_modules/digits.txt" with open (filename) as file: lines = file.readlines() str = '' for line in lines: str += line.strip() print (str [:16 ] + '...' ) print (len (str ))
写入文件 写入文件:调用 open()
时需要提供另一个实参,告诉 Python 你要以写入模式 打开文件。
1 2 3 4 filename = './test.txt' with open (filename, 'w' ) as file_obj: file_obj.write('I love programming.' )
在这个示例中,调用 open()
提供了两个实参:
第一个实参也是要打开的文件的名称
第二个实参 w
告诉 Python,要以写入模式 打开这个文件
读取模式 r
写入模式 w
附加模式 a
读取和写入文件的模式 r+
如果你省略了该实参,Python 将以默认的只读模式打开文件
写入多行 函数 write()
不会在你写入的文本末尾添加换行符!
1 2 3 4 5 6 7 8 filename = 'my_modules/digits.txt' with open (filename, 'w' ) as file_obj: file_obj.write('I love programming.' ) file_obj.write('do you?!' )
追加文件内容 如果你要给文件追加内容,而不是覆盖原有内容,可以附加模式 a
打开文件。
1 2 3 4 filename = 'my_modules/digits.txt' with open (filename, 'a' ) as file_obj: file_obj.write('Yes! I love programming too.' )
异常 Python 使用被称为异常的特殊对象来管理程序执行期间发生的错误。
异常使用 try-except-else
代码块处理,如果你未对异常进行处理,程序将显示 traceback
,其中包含有关异常的报告。
try
代码块中无异常则跳转到 else
代码块中,否则跳转到 except
中进行异常处理。
处理 ZeroDivisionError
异常 1 2 3 4 5 6 7 try : answer = 1 / 3 except ZeroDivisionError: print ("You can't divide by zero!" ) else : print (answer)
处理 FileNotFoundError
异常 1 2 3 4 5 6 7 8 9 filename = 'Gulf.txt' try : with open (filename, 'r' ) as file_obj: print (file_obj.read()) except FileNotFoundError: print ('We could not find the file..' ) else : print ('success reading.' )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def count_file_numbers (filename ): try : with open (filename, 'r' ) as file_object: file_contents = file_object.read() except FileNotFoundError: print ('sorry, the file ' + filename + ' does not exist.' ) else : snippets = file_contents.split() count = len (snippets) print ('the file ' + filename + ' has ' + str (count) + ' words.' ) count_file_numbers('pi_digits.txt' ) count_file_numbers('Gulf.txt' )
存储数据 使用 json.dump()
和 json.load()
存储和获取数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import jsondef remember (filename ): try : with open (filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: username = input ('Input your name, we will remember it! ' ) with open (filename, 'w' ) as f_obj: json.dump(username, f_obj) else : print ("Welcome back, " + username + ' !' ) remember('username.json' )
异常时一声不吭 Python 有一个 pass
语句,可在代码块中使用它来让 Python 什么都不做。
1 2 3 4 5 6 7 8 9 import jsontry : with open ('username.txt' ) as f_obj: username = json.load(f_obj) except FileNotFoundError: pass else : print ('success' )
pass
充当了占位符的作用,提醒你某个地方什么都没做,并且以后也需要在这里做点什么。
测试 测试用例 测试类必须继承 unittest.TestCase
类,这样 Python 才知道如何运行你编写的测试。
注意:测试函数必须以 test_
打头,否则不会被执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 import unittestfrom name_function import Nameclass TestCase (unittest.TestCase): def test_first_last_name (self ): name = Name().get_name('Gulf' , 'Alaska' ) self .assertEqual('Gulf Alaska' , name) unittest.main()
运行 unittest.main()
的测试结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 F ====================================================================== FAIL: test_fist_last_name (__main__.TestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\xxx\PyCharm\pythonProject\www.py" , line 588 , in test_fist_last_name self .assertEqual('Gulf Alaska' , name) AssertionError: 'Gulf Alaska' != 'Gulf Alaska' - Gulf Alaska ? - + Gulf Alaska ---------------------------------------------------------------------- Ran 1 test in 0.001 s FAILED (failures=1 )
测试类 各种断言方法:
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIn(item, list)
assertNotIn(item, list)
方法 setUp()
初始化测试对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import unittestfrom name_function import Nameclass TestCase (unittest.TestCase): def setUp (self ): self .toTestName = Name() def test_first_last_name (self ): name = self .toTestName.get_name('Gulf' , 'Alaska' ) self .assertEqual('Gulf Alaska' , name) unittest.main()
更多 Python 手册