网站框架怎么做,有创意的网站开发,做网站的开发语言,广告公司名称大全最新这次的20道题主要是函数和文件操作综合练习题#xff0c;覆盖函数基础#xff08;定义/调用/参数/返回值#xff09;、文件核心操作#xff08;open/with open、读写模式、数据存取#xff09;#xff0c;难度由浅入深#xff0c;兼顾基础语法和实战应用#xff1a;
一…这次的20道题主要是函数和文件操作综合练习题覆盖函数基础定义/调用/参数/返回值、文件核心操作open/with open、读写模式、数据存取难度由浅入深兼顾基础语法和实战应用一、函数基础题8题聚焦定义/调用/参数/返回值定义一个无参数函数print_hello()功能是打印“Hello Python”并调用该函数。我的答案正确def print_hello(): print(Hello Python) print_hello()定义一个带参数函数calc_square(num)接收一个整数返回该数的平方值调用函数并打印结果如传入5返回25。我的答案正确def calc_square(num): num num * num return num print(calc_square(5))补充代码可以精简为def calc_square(num): return num **2定义一个带默认参数的函数print_info(name, age18)打印“姓名XX年龄XX”分别调用① 仅传name② 传name和age。我的答案正确def print_info(name, age18): print(f姓名{name}年龄{age}) print_info(李四) print_info(张三,13)定义一个可变参数函数sum_nums(*args)接收任意多个整数返回这些数的总和调用函数传入1、3、5、7打印结果。我的答案正确def sum_nums(*ppp):#用输入的数字参数组成元组 return sum(ppp)#元组或列表中数字求和 print(sum_nums(1,3,5,7))定义函数judge_odd_even(num)接收整数返回“奇数”或“偶数”调用函数传入8和9验证结果。我的答案正确def judge_odd_even(num): if num % 2 0: return 偶数 else: return 奇数定义函数filter_list(lst)接收列表返回列表中所有大于10的元素如传入[5,12,8,15,9]返回[12,15]。我的答案错误def filter_list(lst): for i in lst: if i 10: lst.remove(i) return lst print(filter_list([5,12,8,15,9]))正确答案def filter_list(lst): new_lst []#新建空列表存储符合条件的元素不修改原列表 for i in lst: if i 10: new_lst.append(i) return new_lst print(filter_list([5,12,8,15,9])) # 稳定返回[12,15]错误分析遍历列表时用lst.remove(i)会改变列表长度导致元素遗漏如传入[5,12,8,15,9]遍历到 5 时删除→列表变为[12,8,15,9]下一个遍历的是 8 而非 12最终返回[12,15]看似正确但属于 “巧合”若列表为[5,8,12,9,15]会返回[12,15,9]逻辑错误定义函数merge_dict(dict1, dict2)接收两个字典返回合并后的新字典重复键以dict2为准调用示例dict1{“a”:1}, dict2{“b”:2,“a”:3}返回{“a”:3,“b”:2}。我的答案正确def merge_dict(dict1, dict2): dict1.update(dict2)#重复键值以括号内为准 return dict1补充题目要求返回 “新字典”当前写法修改了原 dict1更严谨的写法是先复制 dict1 再合并避免影响原字典参考答案def merge_dict(dict1, dict2): new_dict dict1.copy() # 复制原字典不修改原数据 new_dict.update(dict2) return new_dict定义递归函数factorial(n)计算n的阶乘n! 1×2×…×nn≥1调用函数传入5返回120。我的答案正确def factorial(n):#阶乘的数学性质n n *(n-1)查资料了 if type(n) ! int: return 输入错误请输0或正整数 elif n 0 or n 1: # 终止条件 0 1 1 return 1 elif n 0: return 输入错误请输0或正整数 else: return n * factorial(n-1)#递归需要设置终止条件 print(factorial(5))二、文件操作基础题7题聚焦open/with open/读写模式用with open以“w”模式创建文件test.txt向文件中写入3行内容“第一行Python函数”“第二行文件操作”“第三行基础练习”。我的答案正确with open(test.txt,mode w,encodingutf-8) as f: f.write(第一行Python函数\n第二行文件操作\n第三行基础练习\n) f.flush()用with open以“r”模式读取test.txt文件逐行打印文件内容保留每行的换行格式。我的答案错误with open(test.txt,mode r,encodingutf-8) as f: print(f.read())正确答案with open(test.txt,mode r,encodingutf-8) as f: for line in f: # 逐行遍历文件对象天然按行读取 print(line, end) # end 避免print自动加换行导致空行错误分析题目要求 “逐行打印”当前用 f.read() 一次性读取所有内容并打印整体输出更贴合要求的写法是逐行遍历保留每行独立打印的特性用with open以“a”模式向test.txt末尾追加一行内容“第四行追加内容”追加后读取文件验证。我的答案错误with open(test.txt,mode a,encodingutf-8) as f: f.write(第四行追加内容\n) f.flush()正确答案# 追加内容 with open(test.txt,mode a,encodingutf-8) as f: f.write(第四行追加内容\n) # 读取验证 with open(test.txt,mode r,encodingutf-8) as f: print(追加后文件内容) print(f.read())错误分析题目要求 “追加后读取文件验证”你仅完成追加未添加读取验证代码编写代码读取test.txt文件统计文件的总行数并打印结果。我的答案正确with open(test.txt,mode r,encodingutf-8) as f:#查资料了 lines f.readlines()#将每行读取到列表中 print(len(lines))#列表长度就是行数编写代码创建score.txt文件将列表scores [85,92,78,90,88]中的每个成绩按“一行一个”写入文件。我的答案正确with open(score.txt,mode w,encodingutf-8) as f: scores [85, 92, 78, 90, 88] for s in scores: f.write(str(s) \n)补充你的代码能实现 “一行一个成绩写入文件”仅需小优化变量定义移到 with 外更规范编写代码读取score.txt文件将每个成绩转为整数后计算平均分打印“成绩平均分XX”。我的答案正确with open(score.txt,mode r,encodingutf-8) as f: lst []#初始化列表不能放进循环里 for n in f:#读出所有字符串 n int(n)#转换为整数 lst.append(n)#放入列表 total sum(lst)#求和 average total/len(lst)#和除以列表长度求平均值 print(f成绩平均分{average})补充补充「空文件 / 非数字内容」的容错逻辑参考答案with open(score.txt, moder, encodingutf-8) as f: lst [] for n in f: # 补充去除换行符空行容错避免空行转int报错 n n.strip() # 去掉换行/空格 if not n: # 跳过空行 continue lst.append(int(n)) # 转整数存入列表 # 补充避免空列表除以0报错 if not lst: print(成绩平均分0) else: total sum(lst) average total / len(lst) print(f成绩平均分{average}) # 输出成绩平均分86.6编写代码以“r”模式打开test.txt将文件中“Python”替换为“Java”仅替换第一个匹配项保存后重新读取验证。我的答案错误with open(test.txt,mode r,encodingutf-8) as f: s f.read()#先读后写会变为追加 s s.replace(Python,Java) with open(test.txt,mode r,encodingutf-8) as f: f.write(s)#直接写入会变为覆盖 f.flush()正确答案# r模式打开需要重置指针 with open(test.txt, moder, encodingutf-8) as f: # 1. 读取全部内容 content f.read() # 2. 仅替换第一个匹配项replace的第3个参数指定替换次数 new_content content.replace(Python, Java, 1) # 3. 重置指针到文件开头r模式读后指针在末尾需重置 f.seek(0) # 4. 截断文件清空原有内容避免新内容长度不足时残留旧内容 f.truncate() # 5. 写入新内容 f.write(new_content) # 6. 重置指针到开头重新读取验证 f.seek(0) verify_content f.read() print(替换后文件内容, verify_content)错误分析1、replace(“Python”,“Java”) 会替换所有匹配项不符合 “仅替换第一个” 的要求2、两次打开文件第一次读、第二次写冗余且 r 模式直接 write 未处理指针易导致内容错乱3、未重新读取验证替换结果。三、函数文件操作综合题5题实战场景定义函数write_list_to_file(lst, filename)接收列表和文件名将列表元素按“一行一个”写入指定文件用with open调用函数将[苹果,香蕉,橙子]写入fruit.txt。我的答案正确def write_list_to_file(lst, filename): with open(filename,mode w,encodingutf-8 ) as f: for fruit_name in lst: f.write(str(fruit_name)\n) f.flush() write_list_to_file([苹果,香蕉,橙子],fruit.txt)定义函数read_file_to_list(filename)接收文件名读取文件内容并将每行内容作为元素存入列表去除换行符返回该列表调用函数读取fruit.txt并打印列表。我的答案正确def read_file_to_list(filename): with open(filename,moder,encodingutf-8) as f: lines f.readlines() new_lines [] for fruit_name in lines: fruit_name fruit_name.replace(\n,) new_lines.append(fruit_name) return new_lines print(read_file_to_list(fruit.txt))定义函数count_word_in_file(filename, word)接收文件名和关键词统计关键词在文件中出现的次数忽略大小写调用函数统计test.txt中“操作”出现的次数。我的答案正确def count_word_in_file(filename, word): with open(filename,moder,encodingutf-8) as f: words word.lower()#统一转换为小写以满足不区分大小写查资料 lines f.readlines() total 0 for i in lines: i_lower i.lower() # 每行内容转小写 count i_lower.count(words)#每次都会被重置只保存最后一次查资料 total total count#total是累加变量可以记录p return total print(count_word_in_file(test.txt,操作))定义函数filter_score(filename)读取score.txt中的成绩筛选出≥85的成绩将这些成绩写入新文件high_score.txt并返回高分人数。我的答案正确def filter_score(filename): with open(filename,moder,encodingutf-8) as f: score_list f.readlines() high_score_list [] high_score_total 0 for high_score in score_list: if int(high_score) 85: high_score_list.append(high_score) high_score_total 1 with open(high_score.txt,modew,encodingutf-8) as f: for i in high_score_list: f.write(i) return high_score_total print(filter_score(score.txt))补充1、high_score_list冗余可直接遍历成绩时写入新文件无需先存列表节省内存2、未处理换行符读取的high_score含换行符写入新文件无问题但转换整数时若有空白字符会报错建议加strip()参考答案def filter_score(filename): high_score_total 0 with open(filename,moder,encodingutf-8) as f, open(high_score.txt,modew,encodingutf-8) as f2: for line in f: score int(line.strip()) # 去除换行/空格避免转换报错 if score 85: f2.write(f{score}\n) # 直接写入无需列表中转 high_score_total 1 return high_score_total简易日志记录工具实现功能定义函数write_log(content)接收日志内容字符串用with open以“a”模式写入log.txt日志格式要求每行日志包含“时间 内容”时间用datetime模块import datetime; now datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S)循环接收用户输入的日志内容输入“q”终止每次输入内容后调用write_log()写入日志输入“q”时写入“日志记录终止”并退出。我的答案错误def write_log(content): import datetime now datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S) # 放在循环内记录每次输入的时间戳 if content q: print(日志记录终止) with open(log.txt, moder, encodingutf-8) as f: f.seek(0, 2) # 将指针移动到文档末尾防止被覆盖查资料 f.write(日志记录终止\n) else: with open(log.txt, moder, encodingutf-8) as f: f.seek(0, 2) # 将指针移动到文档末尾防止被覆盖 f.write(now : content \n) while True: log_content input(请输入日志内容完成后按回车输入下一条输入“q”终止输入。) # 放在循环内否则判断条件不会生效 if log_content q: write_log(log_content) break else: write_log(log_content)正确答案import datetime # 全局导入仅执行一次 def write_log(content): now datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S) with open(log.txt, modea, encodingutf-8) as f: # a模式直接追加无需seek if content q: f.write(f{now} : 日志记录终止\n) print(日志记录终止) else: f.write(f{now} : {content}\n) while True: log_content input(请输入日志内容输入“q”终止) if log_content q: write_log(log_content) break write_log(log_content)错误分析1、文件模式错误用r模式读写但 “追加” 应优先用a模式更安全无需手动seek2、模块导入位置冗余import datetime放在函数内每次调用都会重复导入建议放函数外。