python从入门到实践第十章课后练习

本博客详细介绍了Python编程学习的第十章课后练习,涵盖了从读写文件、字符串替换、用户交互到错误处理等多个方面,通过一系列实例帮助巩固Python基础技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python从入门到实践第十章课后练习

10-1 Python 学习笔记

在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:
第一次打印时读取整个文件;
第二次打印时遍历文件对象;
第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。

filename = 'learning_python.txt'
# 读取整个文件
with open(filename) as file_object:
    contents = file_object.read()
    print(contents.rstrip())
    
filename = 'learning_python.txt'
# 遍历文件对象
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
        
filename = 'learning_python.txt'
# 存储列表中再打印
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

learning_python.txt文件内容为:

In python you can 123456789
In python you can 554842645
In python you can 481264813

运行结果

In python you can 123456789
In python you can 554842645
In python you can 481264813
In python you can 123456789
In python you can 554842645
In python you can 481264813
In python you can 123456789
In python you can 554842645
In python you can 481264813

10-2 C 语言学习笔记

可使用方法 replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的’dog’替换为’cat’:

>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'

你刚创建的文件 learning_python.txt 中的每一行,将其中的 Python 都替换为另一门语言的名称,如 C。将修改后的各行都打印到屏幕上。

filename = 'learning_python.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    line = line.replace('python', 'C')
    print(line.rstrip())

运行结果

In C you can 123456789
In C you can 554842645
In C you can 481264813

10-3 访客

编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件 guest.txt 中。

name = input('Please enter your name :')
filename = 'guest.txt'

with open(filename,'w') as file_object:
    file_object.write(name)

运行结果

Please enter your name :wang

guest.txt文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值