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")

浙公网安备 33010602011771号