python 练习10-1:Python学习笔记; 练习10-2:C语言学习笔记; 练习10-3:访客 ;练习10-4:访客名单 ; 练习10-5:调查
练习10-1:Python学习笔记
编写一个程序,它读取这个文件,并将你所写的内容打印三次:
第一次打印时读取整个文件;
第二次打印时遍历文件对象;
第三次打印时将各行存储在一个列表中,再在with代码块外打印它们。
filename = 'pi_digits.txt' with open(filename, encoding='utf-8') as fileobg: content = fileobg.read() print(content.rstrip()) print(content.rstrip()) print(content.rstrip())
with open(filename, encoding='utf-8') as fileobg: for line in fileobg: print(line.rstrip())
with open(filename, encoding='utf-8') as fileobg: lines = fileobg.readlines()
for line in lines: print(line.rstrip())
练习10-2:C语言学习笔记
可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的'dog'替换为'cat':
>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'
读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,比如C。将修改后的各行都打印到屏幕上。
with open(filename, encoding='utf-8') as fileobg: lines = fileobg.readlines() for line in lines: line = line.rstrip() print(line.replace('Python', 'C'))
练习10-3:访客
编写一个程序,提示用户输入名字。用户做出响应后,将其名字写入文件guest.txt中。
name = input('Input Your Name : ') #追加 file = 'guest.txt' with open(file, 'a', encoding='utf-8') as fileobj: fileobj.write(name+'\n') #读取 with open(file, 'r', encoding='utf-8') as fileobj: for line in fileobj: print(line.rstrip())
练习10-4:访客名单
编写一个while循环,提示用户输入名字。用户输入名字后,在屏幕上打印一句问候语,并将一条到访记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
file = 'guest_book.txt' while True: name = input('Input Your Name : ') if name != "quit": print(f"welcome {name.title()} !") with open(file, 'a', encoding='utf-8') as fileobj: fileobj.write(name+'\n') else: break
练习10-5:调查
编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
先将所有的原因保存到一个responses的列表中,然后用for循环来逐个写入 programming_poll.txt 文件
filename = 'programming_poll.txt' responses = [] while True: response = input("\nWhy do you like programming? ") responses.append(response) continue_poll = input("Would you like to let someone else respond? (y/n) ") if continue_poll != 'y': break with open(filename, 'a') as f: for response in responses: f.write(f"{response}\n")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了