教材第十章课后习题 (部分)

代码:

#10.1
print(10.1)
filename = 'test.txt'

print("直接读取")
with open(filename) as file:
	contents = file.read();
	print(contents)
print("逐行存储后读取")
sentences = []
with open(filename) as file:
	for line in file:
		sentences.append(line.rstrip())
for each in sentences:
	print(each)
print("逐行读取")
lines = []
with open(filename) as file:
	lines = file.readlines()
for line in lines:
	print(line.rstrip())

#10.2
print(10.2)
lines2 = []
with open(filename) as file:
	lines2 = file.readlines()
for line in lines2:
	line = line.replace('Python','C++').rstrip()
	print(line)

#10.3
print(10.3)
filename = 'guest.txt'
with open(filename,'w') as file:
	str1 = input("Please input your name:")
	file.write(str1)
with open(filename) as file:
	print(file.read())

#10.4
print(10.4)
with open(filename,'w') as file:
	str1 = input("Your name:")
	while(str1 != 'quit'):
		file.write(str1+'\n')
		str1 = input("Your name:")
with open(filename) as file:
	print(file.read().rstrip())

#10.6
print(10.6)
try:
	num1 = int(input("num1:"))
	num2 = int(input("num2:"))
except ValueError:
	print("ValueError")
else:
	print(num1+num2)

print(10.7)
while True:
	try:
		num1 = input("num1:")
		if(num1 == 'q'):
			break
		num1 = int(num1)
		num2 = input("num2:")
		if(num2 == 'q'):
			break
		num2 = int(num2)
	except ValueError:
		print("ValueError,try again.")
	else:
		print(num1+num2)

输出:

10.1
直接读取
In Python you can play
In Python you can code
In Python you can debug
逐行存储后读取
In Python you can play
In Python you can code
In Python you can debug
逐行读取
In Python you can play
In Python you can code
In Python you can debug
10.2
In C++ you can play
In C++ you can code
In C++ you can debug
10.3
Please input your name:jack
jack
10.4
Your name:pig
Your name:zet
Your name:quit
pig
zet
10.6
num1:1
num2:2
3
10.7
num1:3
num2:4
7
num1:5
num2:6
11
num1:k
ValueError,try again.
num1:5
num2:k
ValueError,try again.
num1:q

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值