Python教程网
--左手Python,右手AI!

牛逼!Python错误、异常和模块(长文系列第四篇)

牛逼!Python错误、异常和模块(长文系列第四篇)

原创 教授 程序员教授 8月7日

系列第四篇主要讲两方面,错误和异常以及模块。在编程时遇见错误信息在所难免,Python中会也有很多种错误信息,常见的两种就是语法错误和逻辑错误,逻辑错误的种类有很多,占据了异常中大部分位置,下面就开始介绍一下这两个概念的相关知识。


错误和异常

语法错误
语法错误英文表示为SyntaxError,后面会跟着一些关于错误的解释信息,方便你查找语句中的bug,如下:

In [5]: print('naitangmao)
  File "<ipython-input-5-d5b793a8884b>", line 1
    print('naitangmao)
                      ^
SyntaxError: EOL while scanning string literal

语法错误顾名思义就是你的代码语句写错了,比如上面这个语句的错误就是少了一个引号。发生错误后,解释器会给出文件的名字和错误行号,以及在错误行下面有一个”^”,这个提示你代码出错的位置,一般会位于箭头前面,这些提示会便于编写者尽快找出错误。

异常
有的时候一行代码在语法上可能没有什么错误,但是执行的时候解释器也会报红,这种错误信息可以称为异常,和语法错误相比,异常的种类更多也更加常见。

举两个简单的例子:

In [6]: print(1/0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-2fc232d1511a> in <module>
----> 1 print(1/0)

ZeroDivisionError: division by zero

都知道0是不能作为分母出现的,所以Python就会给出一个ZeroDivisionError,并提醒你这是一个零除错误。

In [9]: 1+'1'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-d3bd1e37a107> in <module>
----> 1 1+'1'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

整形与字符串之间不存在加法运算,解释器分析出后会给出一个TypeError,这是一个类型错误,并且在后面给出错误的解释。


异常处理

对于Python解释器而言,如果一段程序中某个部分出现了异常,那么其后面的代码将不会被运行,但Python中有方法可以对异常进行处理,让异常不报红,进而帮助整个程序完成运行,这种行为称作捕获异常,以try … except语句组合实现。

In [11]: a = 1;b = '2'
In [12]: try:
    ...:     print(a+b)
    ...: except TypeError:
    ...:     print('类型错误!')
类型错误!

捕获异常实现的过程:

  1. 执行try和except关键字之间的部分
  2. 如果没有异常发生,except子句在try语句执行完毕后就被忽略了。
  3. 如果在 try 子句执行过程中发生了异常,那么该子句其余的部分就会被忽略。如果异常匹配于except关键字后面指定的异常类型,就执行对应的except子句。然后继续执行try/except语句之后的代码。
  4. 如果发生了一个异常,在except子句中没有与之匹配的分支,它就会传递到上一级try语句中。如果最终仍找不到对应的处理语句,它就成为一个未处理异常,终止程序运行,显示提示信息。
    为了避免第4条情况产生,在except语句中可以使用所有异常的父类Exception,这样就囊括了所有异常可能发生的状况:
In [15]: try:
    ...:     print(a+b)
    ...: except Exception as e:
    ...:     print(e)
unsupported operand type(s) for +: 'int' and 'str'

抛出异常
利用raise语句可以主动抛出一个异常,但抛出的异常必须是要继承于Exception的异常类或者异常示例。


In [16]: raise NameError('naitangmao') --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-16-b751158801b2> in <module> ----> 1 raise NameError('naitangmao') NameError: naitangmao

除此上面介绍之外,用户还可以根据自己的需求自己定义异常,不再过多介绍,建议掌握的部分是每种异常出现的原因以及异常处理的方法。


模块

第二部分就是模块,我们有时可能会在不同文件之间利用同一个函数,笨一点的做法就是copy来copy去,Python提供了一个机制可以在将一个文件中的内容导入另一个文件中使用,这样的文件就可以称为模块,需要注意的是并不是任何一个文件都可以当做模块,而必须是包含Python定义和声明的文件。

举一个简单的小例子帮助理解上面这段话,首先可以创建一个odd_num.py文件,然后这个文件中只有一个函数,功能是实现过滤掉一个范围内的偶数:

In [18]: def odd(n):
    ...:     result = []
    ...:     for i in range(n):
    ...:         if i % 2 != 0:
    ...:             result.append(i)
    ...:     return result

然后我们可以在另一个文件中导入这个模块,如果我们想使用这个函数的话,就可以通过模块名.函数名的方法调用该函数,如下:

In [20]: import odd_num
In [21]: odd_num.odd(20)
Out[21]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

如果你只想用一个模块中的某个子模块,那么在导入时就可以指明需要导入的部分,这样子模块就可以单独使用,不必在以模块名.函数名的形式:

In [22]: from odd_num import odd
In [23]: odd(20)
Out[23]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
    ```
如果你还想偷懒的话,可以利用'*'的形式导入,这种写法是导入一个模块中的所有子模块:
```python
In [24]: from odd_num import *
    ```

这种方法往往是不被推荐的,因为会让代码的可读性变差。

如果你有很多自定义的模块,为了更加规范、易找,那么你就可以将这些模块存入一个"包"中,需要注意的是,这个包中比如要有一个名为__init__.py的文件,这个文件可以为空但必须存在,然后导入包中模块的方式就是包名.模块名。

Python本身也有自带的模块库,有一部分模块是内置于解释器之中,然后用户可以直接访问这类模块的接口,很大程度上提高了效率,比如time、sys等等。如果你对于一个模块比较陌生,你可以利用dir()函数搜索某个模块的定义,返回的结果是一个列表,其中包括模块内的方法、可供调用的接口等等。

```python
In [24]:dir(time)
Out[24]:['_STRUCT_TM_ITEMS', '__doc__', '__loader__','__name__','__package__','__spec__','altzone','asctime','ctime','daylight',
'get_clock_info','gmtime','localtime','mktime','monotonic','monotonic_ns','perf_counter','perf_counter_ns','process_time',
'process_time_ns','sleep','strftime','strptime','struct_time','thread_time','thread_time_ns','time','time_ns','timezone','tzname']

综上是对错误和异常、模块两方面常用知识的一些概括,如果你对更高阶的使用感兴趣可以查找Python的官方文档,里面会有更加详细的介绍。


系列推荐:

第一篇

第二篇

第三篇

赞(7)
未经允许不得转载:Python教程网 » 牛逼!Python错误、异常和模块(长文系列第四篇)
分享到: 更多 (0)

评论 113

  1. #1

    Thank you for sharing superb informations. Your website is very cool. I’m impressed by the details that you’ve on this site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my friend, ROCK! I found simply the information I already searched all over the place and simply could not come across. What an ideal web site.

    匿名4个月前 (12-25)回复
  2. #2

    online pharmacy india canadian king pharmacy canadian pharmacies shipping to usa

    匿名2个月前 (02-04)回复
  3. #3

    buy viagra soft no prescription where to buy viagra in australia without prescription pharmacie canadienne

    匿名2个月前 (02-05)回复
  4. #4

    best online canadian pharmacy canadian pharmacies that ship to us brand viagra

    匿名2个月前 (02-06)回复
  5. #5

    canada pharmacy online no script canada drugs online pharmacy intern

    匿名2个月前 (02-07)回复
  6. #6

    online pharmacy viagra buy gerneric viagra pharmacies online

    匿名2个月前 (02-07)回复
  7. #7

    canada pharmacy online reviews compound pharmacy pharmeasy

    匿名2个月前 (02-07)回复
  8. #8

    viagra for men and women for sale food viagra low cost viagra

    匿名2个月前 (02-07)回复
  9. #9

    generic cialis safety health express cialis

    匿名2个月前 (02-10)回复
  10. #10

    buy cialis online paypal buy cialis costco

    匿名2个月前 (02-11)回复
  11. #11

    payday loans in surprise az dbs cash loan for foreigners canberra cash loans

    匿名2个月前 (02-11)回复
  12. #12

    buy cialis fastest delivery service for cialis cialis support 365

    匿名2个月前 (02-11)回复
  13. #13

    viagra online pharmacy usa viagra pharmacy india legal to buy viagra online

    匿名2个月前 (02-12)回复
  14. #14

    words that rhyme with cialis cialis satan hoca cialis commercial taxi

    匿名2个月前 (02-14)回复
  15. #15

    easiest payday loans payday cash advance stockbridge get cash advance without checking account

    匿名2个月前 (02-14)回复
  16. #16

    compare generic cialis prices cialis price nz

    匿名2个月前 (02-15)回复
  17. #17

    cialis shop in australia cialis kopen cialis on line sell

    匿名2个月前 (02-16)回复
  18. #18

    play slots casino bonus codes vegas slots online free casino

    匿名2个月前 (02-16)回复
  19. #19

    national cash advance loan amounts i need a direct lender for a cash advance cash advance with direct lenders only

    匿名2个月前 (02-17)回复
  20. #20

    300 free slots no download no registration quick hits free slots usa no deposit casino bonus codes

    匿名2个月前 (02-20)回复
  21. #21

    best online casinos simslots free slots play casino slots slots free games

    匿名2个月前 (02-20)回复
  22. #22

    casino blackjack https://freecasinoslotsmatic.com/ – free vegas slots online 888 casino download casino online

    匿名2个月前 (02-20)回复
  23. #23

    cialis with dapoxetine without prescription mastercard purchase cialis online canada cialisnonprecription

    匿名1个月前 (02-27)回复
  24. #24

    728tm jpm50 o630

    匿名1个月前 (02-28)回复
  25. #25

    can i take viagra twice a day cialis and viagra flomax and viagra

    匿名1个月前 (03-01)回复
  26. #26

    generic tadalafil united states: http://tadalafilonline20.com/ buy tadalafil

    匿名1个月前 (03-05)回复
  27. #27

    generic tadalafil united states 40 mg tadalafil
    tadalafil pills

    匿名1个月前 (03-06)回复
  28. #28

    buy prescription drugs meds without a doctor prescription

    匿名1个月前 (03-08)回复
  29. #29

    ivermectin human dose ivermectin uk ivermectin to treat covid 19 how does ivermectin kill lice

    匿名1个月前 (03-10)回复
  30. #30

    buy generic 100mg viagra online price of viagra
    viagra amazon

    匿名1个月前 (03-11)回复
  31. #31

    over the counter viagra when will viagra be generic
    100mg viagra

    匿名4周前 (03-12)回复
  32. #32

    buy viagra online canada how much is viagra
    where to buy viagra online

    匿名4周前 (03-12)回复
  33. #33

    viagra over the counter viagra online usa
    viagra from india

    匿名4周前 (03-13)回复
  34. #34

    ventolin dosage albuterol price comparison what is ventolin made out of what is in albuterol

    匿名4周前 (03-13)回复
  35. #35

    how much is viagra viagra price
    п»їviagra pills

    匿名4周前 (03-14)回复
  36. #36

    ivermectin goat dosage ivermectin 18mg what is ivermectin used for how long till worms expelled from seibe after ivermectin

    匿名4周前 (03-14)回复
  37. #37

    viagra amazon viagra over the counter
    п»їviagra pills

    匿名4周前 (03-14)回复
  38. #38

    amoxicillin staph amoxicillin 800 mg price how much amoxicillin for dogs why is amoxicillin preferred over ampicillin

    匿名4周前 (03-15)回复
  39. #39

    ventolin goodrx ventolin online united states is there a generic albuterol inhaler how long should a ventolin inhaler last

    匿名4周前 (03-15)回复
  40. #40

    viagra without a doctor prescription best place to buy generic viagra online
    buying viagra online

    匿名4周前 (03-15)回复
  41. #41

    http://hcialischeapc.com/ – cialis prices

    匿名4周前 (03-15)回复
  42. #42

    buy lasix online buy furosemide tablets uk how does furosemide work in the body when to take furosemide

    匿名4周前 (03-16)回复
  43. #43

    http://diflucanfavdr.com/ – purchase diflucan
    prescription drugs online without doctor

    匿名4周前 (03-16)回复
  44. #44

    amoxicillin stomach pain can i buy amoxicillin can i buy amoxicillin over the counter how long does amoxicillin take

    匿名4周前 (03-16)回复
  45. #45

    propecia prices propecia 5 mg for sale
    what causes ed

    匿名4周前 (03-16)回复
  46. #46

    Thank you for another informative web site. Where else could I am getting that kind of information written in such an ideal approach? I’ve a undertaking that I’m simply now operating on, and I have been on the look out for such info.

    匿名4周前 (03-17)回复
  47. #47

    lasix effects furosemide 40 mg coupon furosemide what does it look like what is the highest dose of lasix for a dog

    匿名3周前 (03-17)回复
  48. #48

    zithromax online order zithromax without prescription
    male enhancement pills

    匿名3周前 (03-17)回复
  49. #49

    http://propeciafavdr.com/ – generic propecia without prescription
    treatment for erectile dysfunction

    匿名3周前 (03-17)回复
  50. #50

    zithromax drug class buy zithromax online no prescription can i buy azithromycin over the counter how to take azithromycin tablets

    匿名3周前 (03-17)回复
  51. #51

    viagra online usa https://viagrapills100.com/ online doctor prescription for viagra

    匿名3周前 (03-18)回复
  52. #52

    azithromycin wiki azithromycin 250 mg tablet buy azithromycin dosage for sinus infection how much azithromycin for chlamydia

    匿名3周前 (03-18)回复
  53. #53

    order viagra online https://viagrapills100.com/ when will viagra be generic

    匿名3周前 (03-19)回复
  54. #54

    missed clomid dose clomid australia online how to take clomid 100mg how much does clomid increase chance of pregnancy

    匿名3周前 (03-19)回复
  55. #55

    doxycycline weight loss doxycycline 100mg online should you take doxycycline with food doxycycline std how long

    匿名3周前 (03-19)回复
  56. #56

    п»їviagra pills https://viagrapills100.com/ 100mg viagra

    匿名3周前 (03-19)回复
  57. #57

    prednisolone phosphate prednisolone sod buy prednisolone online no prescription how does prednisolone work in cats with ibd

    匿名3周前 (03-20)回复
  58. #58

    https://vskamagrav.com/ – kamagra chewable 100 mg canada

    匿名3周前 (03-21)回复
  59. #59

    tadalafil citrate – tadalafil for heart failure tadalafil online reviews

    匿名3周前 (03-21)回复
  60. #60

    clomid hot flashes buy clomid pills how much does clomid cost at walmart how long do clomid pills stay good

    匿名3周前 (03-21)回复
  61. #61

    buy ed pills cheap ed pills from india
    cheap ed pills

    匿名3周前 (03-22)回复
  62. #62

    ed pills online cheap ed pills from canada
    buy ed pills from canada

    匿名3周前 (03-23)回复
  63. #63

    priligy 30 mg avana 50 mg comprar priligy en internet how long dapoxetine last

    匿名3周前 (03-23)回复
  64. #64

    Atguld – annotated bibliography and literature review basics Mpxsob ieujrh

    匿名3周前 (03-23)回复
  65. #65

    diflucan birth control diflucan discount coupon can u buy diflucan over counter what happens if you take diflucan without yeast infection

    匿名3周前 (03-23)回复
  66. #66

    not enough synthroid where to buy synthroid what dosages does synthroid come in what is the difference between synthroid and levothyroxine sodium

    匿名3周前 (03-24)回复
  67. #67

    Fmjico – does cialis lower blood pressure Iiefyv puomam

    匿名2周前 (03-24)回复
  68. #68

    does diflucan work generic for diflucan can you buy diflucan over the counter how long does it take for diflucan to clear a yeast infectio

    匿名2周前 (03-25)回复
  69. #69

    Jqugin – lasix side effects Akiozb rzzjbr

    匿名2周前 (03-25)回复
  70. #70

    http://zithromaxst.com/# where to get zithromax

    匿名2周前 (03-25)回复
  71. #71

    plaquenil medication: order plaquenil – plaquenil 500 mg

    匿名2周前 (03-26)回复
  72. #72

    https://gabapentinst.com/# neurontin drug

    匿名2周前 (03-26)回复
  73. #73

    https://prednisonest.com/# 15 mg prednisone daily

    匿名2周前 (03-26)回复
  74. #74

    Wmsxnl – clomid for sale Dmvdef rsyakt

    匿名2周前 (03-26)回复
  75. #75

    buy prednisone online uk: buy prednisone – prednisone tablets canada

    匿名2周前 (03-27)回复
  76. #76

    http://hydroxychloroquinest.com/# hydroxychloroquine-o-sulfate

    匿名2周前 (03-27)回复
  77. #77

    buy prednisone 10 mg: generic prednisone – buy 10 mg prednisone

    匿名2周前 (03-28)回复
  78. #78

    Ntdlhk – can you buy cialis over the counter in uk Behlhx ehcgcg

    匿名2周前 (03-28)回复
  79. #79

    https://gabapentinst.com/# canada neurontin 100mg discount

    匿名2周前 (03-28)回复
  80. #80

    buy prednisone 5mg canada: generic prednisone – ordering prednisone

    匿名2周前 (03-29)回复
  81. #81

    http://prednisonest.com/# 10 mg prednisone

    匿名2周前 (03-29)回复
  82. #82

    Shawgn – real viagra online canada Xbddpy sblokj

    匿名2周前 (03-29)回复
  83. #83

    https://zithromaxproff.com/# generic zithromax 500mg india
    buy zithromax 1000 mg online

    匿名2周前 (03-30)回复
  84. #84

    https://zithromaxproff.com/# can i buy zithromax over the counter in canada
    zithromax 250 mg

    匿名2周前 (03-30)回复
  85. #85

    http://zithromaxproff.com/# zithromax cost australia
    zithromax order online uk

    匿名2周前 (03-30)回复
  86. #86

    http://zithromaxproff.com/# where can i buy zithromax uk
    cost of generic zithromax

    匿名2周前 (03-31)回复
  87. #87

    Ncqhsi – buy viagra over the counter usa Dtdtgj rqxuoy

    匿名1周前 (04-01)回复
  88. #88

    propecia success stories propecia 1 mg for sale where to buy propecia finasteride when to take propecia

    匿名1周前 (04-01)回复
  89. #89

    Fitlgy – viagra online india Daidfz tjmomn

    匿名1周前 (04-01)回复
  90. #90

    biaxin generic: keflex tablets
    buy doxycycline online

    匿名1周前 (04-02)回复
  91. #91

    omnicef tablets: order noroxin online
    minomycin online

    匿名1周前 (04-02)回复
  92. #92

    Rzvdvg – website for essays Gmoowp poifqk

    匿名1周前 (04-02)回复
  93. #93

    terramycin capsules: cefixime tablets
    clindamycin for sale

    匿名1周前 (04-03)回复
  94. #94

    Voeldl – finasteride generic reviews Xouwbv viptla

    匿名7天前回复
  95. #95

    clomid and metformin metformin without script metformin long term side effects how does metformin help you lose weight

    匿名7天前回复
  96. #96

    neurontin and lyrica cost of neurontin 600 mg does neurontin increase blood pressure what is gabapentin for pain

    匿名7天前回复
  97. #97

    generic pills india: reputable online pharmacies in india generic pills india

    匿名6天前回复
  98. #98

    indian online pharmacies review: buy prescriptions from india pharmacy india pharmacy mail order

    匿名6天前回复
  99. #99

    neurontin tablet can i buy gabapentin in mexico what are long term effects of neurontin how to taper off gabapentin

    匿名6天前回复
  100. #100

    Xfseyk – ou acheter du viagra sans ordonnance Sthfwd dhtcif

    匿名6天前回复
  101. #101

    metformin kidney metformin online india will metformin make me lose weight when metformin stops working

    匿名5天前回复
  102. #102

    best india pharmacy: order medications online from india buy prescriptions from india pharmacy

    匿名5天前回复
  103. #103

    paxil horror stories paxil 20 mg online paxil reviews for social anxiety what is the difference between paxil cr and paxil

    匿名4天前回复
  104. #104

    best male erectile dysfunction pill: https://edpillsonline24.com/# order erectile dysfunction pills

    匿名4天前回复
  105. #105

    10mg paxil paroxetine tab 30mg can paxil not work for you what antidepressant can i take in place of paxil

    匿名3天前回复
  106. #106

    cialis pills: https://edpillsonline24.com/# red erectile dysfunction pill

    匿名3天前回复
  107. #107

    plaquenil for crohn’s hydroxychloroquine buy can you combine doxycycline hyclate with plaquenil what is a screening eye exam for plaquenil

    匿名3天前回复
  108. #108

    levitra pills: pills for erectile dysfunction best male erectile dysfunction pill

    匿名2天前回复
  109. #109

    order erectile dysfunction pills online: https://edpillsonline24.com/# best ed pills

    匿名2天前回复
  110. #110

    free adult personals
    completely free dating site

    匿名2天前回复
  111. #111

    ed meds: https://edpillsonline24.com/# best male erectile dysfunction pill

    匿名24小时前回复
  112. #112

    Isnnmd – sildenafil citrate tablets uses in telugu Xawzoq mnoooj

    匿名23小时前回复
  113. #113

    how much is viagra: non prescription viagra viagra online without prescription

    匿名18小时前回复