Bug-type exception handling common to python exceptions

Common types of bugs

1. SyntaxError caused by carelessness

1,

age=input('Please enter your age:')
if age>=18:
    print("Adults need to do things...")
#Error, TypeError:'>='not supported between instances of'str' and'int'
#Because the input input return value is a string, it cannot be compared to an integer type number
#Solution: Add int() before the input, convert the input number to integer type, and you can compare the data
age=int(input('Please enter your age:'))
if age>=18:
    print("Adults need to do things...")

2,

while i<10:
    print (i)
#Loop statement error, cause of error, no initial value of loop variable, no increment of loop variable, then use brackets is not standard, use Chinese brackets
#Solution: Add the initial value of the fantasy variable, add the increment of the loop variable, and correct the nonstandard brackets (use Chinese brackets)
#Circulation has three elements

i=1   #The starting value of a loop variable
while i < 10:   #Loop Conditional Statement
    print(i)
    i+=1   #Incremental Variables

3,

for i in range(3):
    uname =input("Please enter a user name:")
    upwd=input("Please input a password:")
    if uname="admin" and upwd=pwd:
        print("Landing success!")
    else
        print("Input Error")
else
    print("Sorry, three typing errors")
#Error, SyntaxError: invalid syntax. Maybe you meant'=='or':=' instead of'='?
#There are many errors, = is assignment, == is comparison, if statement uses = assignment when comparing, so there are errors, and the content admin of undefined comparison is not added after the else statement:
#Solution: Replace = with== at the if statement comparison because = is an assignment, == is a comparison, or add a variable to compare before the loop starts, followed by a colon after the else statement:
admin="hua"
pwd="123456"
for i in range(3):
    uname =input("Please enter a user name:")
    upwd=input("Please input a password:")
    if uname==admin and upwd==pwd:
        print("Landing success!")
    else:
        print("Input Error")
else:
    print("Sorry, three typing errors")
A treasure trove of self-checks where carelessness leads to errors:
1. The colon at the end is missing, such as if statement, loop statement, else clause, etc.
2. Incorrect indentation. The indentation is not indented but should not.
3. Writing English symbols into Chinese symbols, such as quotation marks, colons, brackets
 4. When stitching strings, stitch strings and numbers together
 5. There are no variables defined, such as while's loop condition variable
 Mixing of'=='comparison operator and'=' assignment operator
2. Error Bug Caused by Unskilled Knowledge
1. IndexError on index crossing
lst=[11,22,33,44]
print(lst[4])
#Error, IndexError: list index out of range index is out of bounds, although there are four numbers, but the index is not calculated from the beginning, positive index is calculated from 0, negative index is calculated from -1
#Solution: Rewrite to the correct index
lst=[11,22,33,44]
print(lst[3])

2,

lst=[]
lst=append("A","B","C")
print((lst))
#Error, NameError: name'append'is not defined by the wrong method uses the append() function
#Solution, master the correct techniques for using functions, use functions instead of using = calls. To call a function, and the append() function can only add one element at a time
lst=[]
lst.append("A")
lst.append("B")
lst.append("C")
print((lst))  #Return values ['A','B','C']
#Unskilled knowledge points lead to errors, the only solution is to practice
#3. Solutions to problems caused by unclear ideas
1. Use print() function
 print out the wrong code, comment out the problematic code, debug step by step, and output the desired result
 2. Use "#" to temporarily unregister part of the code 

Solution: Practice more and master the basics
4. Passive pitfall: Program code logic is correct, knowledge crashes due to user error or some "exceptions"

#Solution to passive pit dropping problem
 #python provides an exception handling mechanism that allows the program to continue running even if a replenishment occurs and then digests internally
Exception capture handling try: except xxx: statement XXX is the error type

try: for putting error-prone code in
 Exceept is used to handle exceptions and output subsequent code normally, so that the code does not end with an error. Multiple except statements can appear to handle multiple exception types.
How to use:
try:
Put error-prone code in it
 Error prone code
 Error prone code
 Possible types of except:
Print (the word used to prompt after catching an exception)
Possible types of except:
Print (the word used to prompt after catching an exception)
#General Code
a=int(input("Please enter the first integer:"))
b=int(input("Please enter the second integer:"))
result=a/b
print("The results are:",result)
#Errors are very likely to occur, resulting in termination of subsequent programs, such as division cannot enter 0, cannot enter English, as long as it is entered, the program will end with an error
#So try:except is required
try:    #Put error-prone code in
    a=int(input("Please enter the first integer:"))
    b=int(input("Please enter the second integer:"))
    result=a/b
    print("The results are:",result)
except ZeroDivisionError:   #Exceptions that are divisible by 0 are not allowed (exception types occur when a program errors, and when this exception type is put in, the exception is handled automatically without terminating the program with an error)
    print("Sorry, division is not allowed to be zero")  #Tips after the exception occurs
except ValueError:    #input exception. input in int brackets can only enter a number string, not a string
    print("Only numeric strings can be entered")   #Tips after the exception occurs
print("Program End")    #All possible exceptions to the program are written out in except, so whatever exceptions occur, the following programs run as well

Keywords: Python Back-end

Added by Rayne on Thu, 03 Feb 2022 19:31:36 +0200