跟我一起敲代码 发表于 2021-7-17 14:56:58

python 课后作业

def file_compare(f1_name,f2_name):
    f1 = open(f1_name)
    f2 = open(f2_name)

    count = 0
    differs = []

    for each in f1:
      each2 = f2.readline()
      if each == each2:
            count += 1
      else:
            differs.append(count)
            
    f1.close()
    f2.close()
    return differs


f1_name = input('请输入第一个文件名:')
f2_name = input('请输入第二个文件名:')

differs = file_compare(f1_name,f2_name)

if len(differs) == 0:
    print('没有不同')
else:
    print('文件%s和文件%s共有%d个不同' % (f1_name,f2_name,len(differs))
    for each in differs:
      print('第%d行不同' % each)



个人感觉没有问题,为啥倒数第二行'for each in differs:',每次运行都会把冒号标红,蹦出来个invalid syntax

Twilight6 发表于 2021-7-17 15:09:22



因为你第 28 行少了个右括号:

def file_compare(f1_name, f2_name):
    f1 = open(f1_name)
    f2 = open(f2_name)

    count = 0
    differs = []

    for each in f1:
      each2 = f2.readline()
      if each == each2:
            count += 1
      else:
            differs.append(count)

    f1.close()
    f2.close()
    return differs


f1_name = input('请输入第一个文件名:')
f2_name = input('请输入第二个文件名:')

differs = file_compare(f1_name, f2_name)

if len(differs) == 0:
    print('没有不同')
else:
    print('文件%s和文件%s共有%d个不同' % (f1_name, f2_name, len(differs)))
    for each in differs:
      print('第%d行不同' % each)
页: [1]
查看完整版本: python 课后作业