在 Python 中,else 语句能跟哪些语句进行搭配?
- if…else
- for
- 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)