Why do we need the “finally” clause in Python?

前端 未结 14 1987
感情败类
感情败类 2020-11-28 16:58

I am not sure why we need finally in try...except...finally statements. In my opinion, this code block

try:
    run_code1()
except          


        
14条回答
  •  野性不改
    2020-11-28 17:40

    Run these Python3 codes to watch the need of finally:

    CASE1:

    count = 0
    while True:
        count += 1
        if count > 3:
            break
        else:
            try:
                x = int(input("Enter your lock number here: "))
    
                if x == 586:
                    print("Your lock has unlocked :)")
    
                    break
                else:
                    print("Try again!!")
    
                    continue
    
            except:
                print("Invalid entry!!")
            finally:
                print("Your Attempts: {}".format(count))
    

    CASE2:

    count = 0
    
    while True:
        count += 1
        if count > 3:
            break
        else:
            try:
                x = int(input("Enter your lock number here: "))
    
                if x == 586:
                    print("Your lock has unlocked :)")
    
                    break
                else:
                    print("Try again!!")
    
                    continue
    
            except:
                print("Invalid entry!!")
    
            print("Your Attempts: {}".format(count))
    

    Try the following inputs each time:

    1. random integers
    2. correct code which is 586(Try this and you will get your answer)
    3. random strings

    ** At a very early stage of learning Python.

提交回复
热议问题