1、else与while语句搭配

def showMaxFactor(num):
    count = num // 2  #判断是素数,只需依次判断当前数num除以1到(num // 2)都不能整除即可
    while count > 1:
        if num % count == 0: #判断是否整除
            print('%d最大的约数是%d' % (num, count))
            break  #跳出循环后else并不执行
        count -= 1
    else:  #当while循环完全被执行完了,没有给中途跳出(即break),就会执行else语句
        print('%d是素数!' % num)

num = int(input('请输入一个数:'))
showMaxFactor(num)

运行输出:
=============================== RESTART: D:/Program Files/1/34讲/0831_2.py ===============================
请输入一个数:25
25最大的约数是5
>>> 
=============================== RESTART: D:/Program Files/1/34讲/0831_2.py ===============================
请输入一个数:11
11是素数!
>>>

注:else与for语句搭配同else与while语句搭配一样

2、else与异常语句搭配
只要try语句块里没有出现任何异常,就会执行else语句块里的内容

try:
    print(int('abc'))
except ValueError as reason:  #如果程序有异常时执行
    print('出错了:' + str(reason))
else:  #程序无异常时执行
    print('没有任何异常!')
运行输出:
出错了:invalid literal for int() with base 10: 'abc'

try:
    print(int('123'))
except ValueError as reason:  #如果程序有异常时执行
    print('出错了:' + str(reason))
else:  #程序无异常时执行
    print('没有任何异常!')
运行输出:
123
没有任何异常!

3、简洁的with语句

try:
    f = open('test.txt', 'w') #不存在test.txt
    print('0')
    for each_line in f: #这里报错的原因是文件以'w'形式打开创建的,文件里面没有内容,**无法用each_line遍历**
        print('1')
        print(each_line)
        print('2')
except (OSError, TypeError) as reason:
    print('出错了\n原因是:' + str(reason))
finally:
    f.close()
    print('3')

运行输出:
0
出错了
原因是:not readable
3

简洁的with语句(with会自动帮你关闭文件)
try:
    with open('test.txt', 'w') as f: #这里with会关注文件open了什么时候没有再使用,with自动帮你关闭文件
        for each_line in f:
            print(each_line)
except (OSError, TypeError) as reason:
    print('出错了\n原因是:' + str(reason))

测试题:

0. 在 Python 中,else 语句能跟哪些语句进行搭配?

答:在 Python 中,else 语句不仅能跟 if 语句搭,构成“要么怎样,要么不怎样”的语境;Ta 还能跟循环语句(for 语句或者 while 语句),构成“干完了能怎样,干不完就别想怎样”的语境;其实 else 语句还能够跟我们刚刚讲的异常处理进行搭配,构成“没有问题,那就干吧”的语境。

1. 请问以下例子中,循环中的 break 语句会跳过 else 语句吗?

python素数判断for python素数判断并输出while语句_while语句


答:会,因为如果将 else 语句与循环语句(while 和 for 语句)进行搭配,那么只有在循环正常执行完成后才会执行 else 语句块的内容。

2. 请目测以下代码会打印什么内容?

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

答:只有 except 语句中的内容不被打印,因为 try 语句块中并没有异常,则 else 语句块也会被执行。

ABC

GHI

JKL

3. 使用什么语句可以使你不比再担心文件打开后却忘了关闭的尴尬?

答:使用 with 语句。

python素数判断for python素数判断并输出while语句_while语句_02


4. 使用 with 语句固然方便,但如果出现异常的话,文件还会自动正常关闭吗?

答:with 语句会自动处理文件的打开和关闭,如果中途出现异常,会执行清理代码,然后确保文件自动关闭。

5. 你可以换一种形式写出下边的伪代码吗?

python素数判断for python素数判断并输出while语句_文件名_03


答:with 语句处理多个项目的时候,可以用逗号隔开写成一条语句

with A() as a, B() as b:
    suite

动动手:

0. 使用 with 语句改写以下代码,让 Python 去关心文件的打开与关闭吧。

def file_compare(file1, file2):
    f1 = open(file1)
    f2 = open(file2)
    count = 0 # 统计行数
    differ = [] # 统计不一样的数量

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

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

file1 = input('请输入需要比较的头一个文件名:')
file2 = input('请输入需要比较的另一个文件名:')

differ = file_compare(file1, file2)

if len(differ) == 0:
    print('两个文件完全一样!')
else:
    print('两个文件共有【%d】处不同:' % len(differ))
    for each in differ:
        print('第 %d 行不一样' % each)

答:使用 with 语句处理文件可以减少需要编写的代码量和粗心的错误。

def file_compare(file1, file2):
    count = 0  #统计行数
    differ = []  #统计不一样的数量

    with open(file1) as f1, open(file2) as f2:
        for line1 in f1:
            line2 = f2.readline()
            count += 1
            if line1 != line2:
                differ.append(count)
                
    return differ

file1 = input('请输入需要比较的头一个文件名:')
file2 = input('请输入需要比较的另一个文件名:')
differ = file_compare(file1, file2)

if len(differ) == 0:
    print('两个文件完全一样!')
else:
    print('两个文件共有【%d】处不同:' %len(differ))
    for each in differ:
        print('第%d行不一样' %each)

1. 你可以利用异常的原理,修改下面的代码使得更高效率的实现吗?

print('|--- 欢迎进入通讯录程序 ---|')
print('|--- 1:查询联系人资料  ---|')
print('|--- 2:插入新的联系人  ---|')
print('|--- 3:删除已有联系人  ---|')
print('|--- 4:退出通讯录程序  ---|')

contacts = dict()

while 1:
    instr = int(input('\n请输入相关的指令代码:'))
    
    if instr == 1:
        name = input('请输入联系人姓名:')
        if name in contacts:
            print(name + ' : ' + contacts[name])
        else:
            print('您输入的姓名不再通讯录中!')

    if instr == 2:
        name = input('请输入联系人姓名:')
        if name in contacts:
            print('您输入的姓名在通讯录中已存在 -->> ', end='')
            print(name + ' : ' + contacts[name])
            if input('是否修改用户资料(YES/NO):') == 'YES':
                contacts[name] = input('请输入用户联系电话:')
        else:
            contacts[name] = input('请输入用户联系电话:')

    if instr == 3:
        name = input('请输入联系人姓名:')
        if name in contacts:
            del(contacts[name])         # 也可以使用dict.pop()
        else:
            print('您输入的联系人不存在。')
            
    if instr == 4:
        break

print('|--- 感谢使用通讯录程序 ---|')

答: