python练习题else和with的用法

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

  1. if…else
  2. for
  3. while

与while搭配

def showMaxFactor(num):
    count = num // 2
    while count > 1:
        if num % count == 0:
            print('%d最大的约数是%d' % (num, count))
            break
        count -= 1
    else:
        print('%d是素数!' % num)

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

else 语句与循环语句(while 和 for 语句)进行搭配,那么只有在循环正常执行完成后才会执行 else 语句块的内容
使用with语句可以不必担心文件打开后忘记关闭
with 语句会自动处理文件的打开和关闭,如果中途出现异常,会执行清理代码,然后确保文件自动关闭

try:
    with open('data.txt', 'w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出错啦:' + str(reason))

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

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

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

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

        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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值