else statement is related to with statement

Keywords: Python

Notes:
reference resources: http://blog.csdn.net/junwei0206/article/details/45065491
1. Use of else statement:
1) Match with if statement
2) In the while and for loops, execute only after the loop is completed. If break is used in the loop, else does not execute.

#*************************************************#  
#      Determine the maximum common divisor of a given number, and print if it is a prime number         #  
#*************************************************#  
def showMaxFactor(num):  
    count = num//2  
    while count > 1:  
        if num %count == 0:  
            print('%d The greatest divisor is%d'%(num,count))  
            break  
        count -= 1  
    else:  
        print('%d It's prime!'%num)  

num = int(input('Please enter a number:'))  
showMaxFactor(num)  

3) Use with exception handling statements: (if there are no errors, print out 'no errors!')

try:  
    print(int('abc'))  
except ValueError as reason:  
    print('Something went wrong:' + reason)  
else:  
    print('No exceptions!')  

Please check visually what the following code will print?

try:  
    print('ABC')  
except:  
    print('DEF')  
else:  
    print('GHI')  
finally:  
    print('JKL')  

Answer: only the content in the except statement is not printed, because there is no exception in the try statement block, the else statement block will also be executed.
ABC
GHI
JKL

2. with statement: (avoids the trouble of forgetting to close the opened file)

#*********************************************#  
#        Exception handling cooperation with Sentence                   #  
#            It can avoid the situation that the opened file is not closed       #  
#*********************************************#  
try:  
    with open('data.txt','w') as f:  
        for each_line in f:  
            print(each_line)  
except OSError as reason:  
    print('Something went wrong:' + str(reason))  

Hands on:

  1. Use the with statement to rewrite the following code. Let Python care about the opening and closing of files.
def file_compare(file1,file2):  
    f1 = open(file1)  
    f2 = open(file2)  
    count = 0#Count lines  
    differ = []#Count different quantities  

    for line1 in f1:  
        line2 = f2.readline()  
        count += 1  
        if line1 != line2:  
            differ.append(count)  

    f1.close()  
    f2.close()  
    return differ  

file1 = input('Please enter the first filename to compare:')  
file2 = input('Please enter another file name to compare:')  

differ = file_compare(file1,file2)  

if len(differ) == 0:  
    print('The two files are exactly the same!')  
else:  
    print('Two files in common[%d]Differences:'%len(differ))  
    for each in differ:  
        print('The first%d It's different'%each)  

After modification:

def file_compare(file1,file2):  
    with open(file1) as f1,open(file2) as f2:  
        count = 0#Count lines  
        differ = []#Count different quantities  

        for line1 in f1:  
            line2 = f2.readline()  
            count += 1  
            if line1 != line2:  
                differ.append(count)  
    return differ  

file1 = input('Please enter the first filename to compare:')  
file2 = input('Please enter another file name to compare:')  

differ = file_compare(file1,file2)  

if len(differ) == 0:  
    print('The two files are exactly the same!')  
else:  
    print('Two files in common[%d]Differences:'%len(differ))  
    for each in differ:  
        print('The first%d It's different'%each)  
  1. Can you use the exception principle to modify the following code for a more efficient implementation?
print('|--- Welcome to the address book program ---|')  
print('|--- 1: Query contact information  ---|')  
print('|--- 2: Insert new contact  ---|')  
print('|--- 3: Delete existing contacts  ---|')  
print('|--- 4: Exit address book program  ---|')  

contacts = dict()  

while 1:  
    instr = int(input('\n Please enter the relevant instruction code:'))  

    if instr == 1:  
        name = input('Please enter contact name:')  
        if name in contacts:  
            print(name + ': ' + contacts[name])  
        else:  
            print('The name you entered is not in the address book!')  

    if instr == 2:  
        name = input('Please enter contact name:')  
        if name in contacts:  
            print('The name you entered already exists in the address book -->',end='')  
            print(name + ': ' + contacts[name])  
            if input('Modify user data or not( YES/NO): ') == 'YES':  
                contacts[name] = input('Please enter the user contact number:')  

        else:  
            contacts[name] = input('Please enter the user contact number:')  

    if instr == 3:  
        name = input('Please enter contact name:')  
        if name in contacts:  
            del(contacts[name])     #You can also use dict.pop()  
        else:  
            print('The contact you entered does not exist.')  

    if instr == 4:  
        break  

print('|--- Thank you for using the address book program ---|')  

A: the code using conditional statements is very straightforward, but not efficient. Because the program will access the key of the dictionary twice to determine whether it exists (for example, if name in contacts) (for example, print(name + ':' + contacts[name])).

If we use the exception solution, we can simply avoid using in to determine whether the key exists in the dictionary every time. Because as long as the key does not exist in the dictionary, KeyError will be triggered
For this feature, we can modify the code as follows:

print('|--- Welcome to the address book program ---|')  
print('|--- 1: Query contact information  ---|')  
print('|--- 2: Insert new contact  ---|')  
print('|--- 3: Delete existing contacts  ---|')  
print('|--- 4: Exit address book program  ---|')  

contacts = dict()  

while 1:  
    instr = int(input('\n Please enter the relevant instruction code:'))  

    if instr == 1:  
        name = input('Please enter contact name:')  
        try:  
            print(name + ': ' + contacts[name])  
        except KeyError:  
            print('The name you entered is not in the address book!')  

    if instr == 2:  
        name = input('Please enter contact name:')  
        try:  
            print('The name you entered already exists in the address book -->',end='')  
            print(name + ': ' + contacts[name])  
            if input('Modify user data or not( YES/NO): ') == 'YES':  
                contacts[name] = input('Please enter the user contact number:')  

        except KeyError:  
            contacts[name] = input('Please enter the user contact number:')  

    if instr == 3:  
        name = input('Please enter contact name:')  
        try:   
            del(contacts[name])     #You can also use dict.pop()  
        except KeyError:  
            print('The contact you entered does not exist.')  

    if instr == 4:  
        break  

print('|--- Thank you for using the address book program ---|')  

Posted by Andrew B on Tue, 05 May 2020 03:09:57 -0700