More , Please visit mine Personal blog .
When we write a program, what we like most is that the program prints out the results we want .
The biggest fear is that the program doesn't run as we expected , When it's over, there are a lot of error messages .
This chapter is about python Error messages in . There are many types of error messages , Here are two common error messages :
Let's first look at what a grammatical error is . Remember what we said before for Loop statement , Must have a colon , If you don't take a colon , Will report grammatical errors .
list = [' Apple ', ' watermelon ', ' grapes ']
for lt in list
print(lt)
for lt in list
^
SyntaxError: invalid syntax
If there is no indentation in the loop statement , You can also report grammatical errors .
list = [' Apple ', ' watermelon ', ' grapes ']
for lt in list:
print(lt)
print(lt)
^
IndentationError: expected an indented block
The error message is very clear , Just follow the prompts to modify .
If the grammar is correct , If there is a logic error in the program , Then it will be wrong , Such errors are logical exceptions .
For example, calculation 1/0, We know 0 Is not a divisor , This is a logical error , The program will report an exception .
a = 1 / 0
print(a)
a = 1 / 0
ZeroDivisionError: division by zero
Take this example , The program will report an exception , say b This thing has no definition , I don't know what it is .
a = 1 / b
print(a)
a = 1 / b
NameError: name 'b' is not defined
Sometimes we suspect that some code may report an error , Or worry about reporting errors , But I don't want the program to break . Then we can use try Statement to catch exception information .
try:
1/0
except:
print(' A program error was reported ')
print(' No matter what 1/0 Isn't it , I don't want the program to stop ')
As in the example above , although 1/0 Is a logical error , But the program doesn't report a mistake , The program will output these two sentences in turn , Then the program exits normally .
We can also classify the error information according to the difference .
try:
a/0
except ZeroDivisionError:
print('0 Can't be divisor ')
except NameError:
print(' Variables are not defined ')
As in the example above , We can capture... Separately 0 Can't be divisor
and Variables are not defined
These two types of abnormal information .
Of course , We can also add else sentence , When try There is nothing wrong with the content in the , perform else Code in .
try:
a/0
except ZeroDivisionError:
print('0 Can't be divisor ')
except NameError:
print(' Variables are not defined ')
else:
print(' There is no mistake ')
Try adding... To the following code try sentence , And capture ZeroDivisionError
、NameError
abnormal .
x = int(input(" Please enter an integer : "))
y = 1 / x
print(x + " What's the reciprocal :" + y)
Official account : Pangao will accompany you to learn programming , reply 020, Get the answer to the exercise .