Da Shu Xie python training camp punch in notes Task03

1, Summary of learning points

① python standard exception summary ② python standard warning summary ③ try exception statement ④ try exception finally statement ⑤ try exception else statement ⑥ raise statement

2, Learning content

1.Python standard exception summary

There are hierarchical relationships within the exception system. Some relationships in Python exception system are as follows:

2.Python standard warning summary

3.try - except statement

try:
    Detection range (where errors may occur)
except Exception[as reason]:
    Handling code after exception (proposed solution if error occurs)

technological process:

① Execute the try statement first

② If there is no exception, only the try statement is executed and the except clause is ignored

③ If there is an exception (an exception occurs during the execution of the try clause), the rest of the try clause will be ignored

        (1) If the name after exception matches the exception type, the corresponding exception clause will be executed, and finally the code after the try statement will be executed

        (2) If the name after except does not match the exception type, the exception will be passed to the upper try.

be careful:

① A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed.

② When raising multiple exceptions, pay attention to the hierarchical relationship, from the most targeted exceptions to the most common exceptions. (see hierarchy diagram) (e.g. KeyError before LookupError)

③ An exception statement can handle multiple exceptions at the same time. These exceptions will be placed in a bracket as a tuple.

[example]

try:
    s = 1 + '1'
    int("abc")
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print('Something went wrong!\n as a result of:' + str(error))

# Something went wrong!
# The reason is: unsupported operand type(s) for +: 'int' and 'str'

4.try - except - finally statement

try:
    Detection range
except Exception[as reason]:
    Handling code after exception
finally:
    Code that will be executed anyway

① The finally clause is executed regardless of whether an exception occurs in the try clause.

② If an exception is thrown in the try clause and no exception intercepts it, the exception will be thrown after the finally clause is executed.

5.try - except - else statement

try:
    Detection range
except:
    Handling code after exception
else:
    If there are no exceptions, execute this code

  ① If no exception occurs during the execution of the try clause, Python executes the statement after the else statement. If an exception occurs, the statement after the except statement is executed.

② Using exception without any exception type is not a good way. We can't identify the specific exception information through the program because it catches all exceptions.

[example]

try:
    Detection range
except(Exception1[, Exception2[,...ExceptionN]]]):
   If one of the above exceptions occurs, execute this code
else:
    If there are no exceptions, execute this code

Note: the existence of else statement must be based on the existence of exception statement. Using else statement in try statement without exception statement will cause syntax error.

6.raise statement

Python uses the raise statement to throw a specified exception.

[example]

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    
# An exception flew by!

3, Learning problems and solutions (own problems + after-school questions)

[problems encountered]

① From the most targeted exceptions to the most common exceptions.

My understanding is to put the most contained before the least contained, such as BaseException after (?)

Watching the video proves that my understanding is right: I spent more than 20000 yuan to buy a complete set of Python tutorials. Now I'll share it with you from getting started to mastering (Python full stack development tutorial)_ Beep beep beep_ bilibili

[after class question] number guessing game

Idea:

① First, I learned how to obtain random numbers: (take an integer between 0-100)

import random
a=1
b=100
print(random.randint(a,b))
import random
random.randint(1,100)

② Output "guess an integer between 0 and 100"

temp = input ("Guess an integer between 0 and 100")

③ Use the circular statement while to have the opportunity to guess numbers many times

④ Use the if statement to judge "too big", "too small", "Congratulations, you guessed the number is"

final

[code I wrote]

import random

counts = 0
answer = random.randint(1,100)

while counts == 0:
    temp = input ("Guess an integer between 0 and 100")
    guess = int(temp)
    counts = 0
    if guess == answer:
        print("Congratulations, you guessed the number",answer)
    else:
        if guess < answer:
            print("Too small")
        else:
            print("too big")

[output effect]

[questions]

① Guessing the number correctly did not end the process

Try to solve: try to add break after the statement that guesses the number correctly, and then it won't run again, and then the * sign appears in front of it

② Before the user guesses every time, the program does not output. How many guesses does the user make

③ The try statement is not used to display: if the user enters a number at all, the program will tell the user "the input is invalid"

try:
    ......
except ValueException:
    print('Invalid input')

[modified code]

After a little modification, the effect has solved the problem ③ there are still problems ① and ②:

import random

counts = 0
answer = random.randint(1,100)

try:
    while counts == 0:
        temp = input ("Guess an integer between 0 and 100")
        guess = int(temp)


        if guess == answer:
            print("Congratulations, you guessed the number",answer)
        else:
            if guess < answer:
                print("Too small")
            else:
                print("too big")
except ValueError:
    print('Invalid input')

[output effect]

 

 

4, Learning, thinking and summary

1. Put forward some thoughts on try and except

try the following is where errors may occur

Exception is a solution to an error

2. About the try except else finally statement

3. Learned the method of obtaining random numbers

import random
a=1
b=100
print(random.randint(a,b))
import random
random.randint(1,100)

4. The most common exception types and examples in Python:

#(1) Abnormal mathematical operation
#ZeroDivisionError divide (or modulo) zero (all data types)
print(10/0)
#IndexError, the index starts from 0, and the fourth input is 3
lst=[11,22,33,44]
print(lst[4])
#KeyError (this key is not in the mapping)
dic={'name':'Zhang San','age':20}
print(dic['gender'])
#NameError object not declared / initialized (no properties)
print(num)
#Syntax error Python syntax error
int a=20
#ValueError passed in an invalid parameter
a=int('hello')
#hello is a string and cannot be converted to a decimal integer

5. Summary

① Trying to write a piece of code by yourself is still very rewarding, although there are still many problems to be solved and learned

② This study takes about four hours to add notes. The reference videos are: I spent more than 20000 yuan to buy a complete set of Python tutorials. Now I'll share it with you from getting started to mastering (Python full stack development tutorial)_ Beep beep beep_ bilibili   I have a deeper understanding

Tags: Python

Posted on Tue, 30 Nov 2021 20:45:35 -0500 by baby_g