python第十章习题

10-1

文件内容:

In Python you can
output a string
define a class
do with file

代码:

with open('py.txt') as file:
	contents = file.read()

print(contents)

for content in contents:
	print(content)

with open('py.txt') as file:
	lines = file.readlines()

print(lines)

输出结果:

In Python you can
output a string
define a class
do with file
In Python you can
output a string
define a class
do with file
['In Python you can\n', 'output a string\n', 'define a class\n', 'do with file']

10-4

代码:

name = ""
with open('guest_book','w') as file:
	while True:
		name = input("What is you name?(q to quit):")
		if name == "q":
			break
		print("Hello," + name)
		file.write("Hello," + name +"\n")

输入:

What is you name?(q to quit):Eric
Hello,Eric
What is you name?(q to quit):Kangkang
Hello,Kangkang
What is you name?(q to quit):Mary
Hello,Mary
What is you name?(q to quit):q

guest_book.txt:

Hello,Eric
Hello,Kangkang
Hello,Mary

10-6

代码:

first = ""
second = ""
while True:
	flag = True
	first = input("The first number is:")
	try:
		first_number = int(first)
	except ValueError:
		print("The input should be a number!")
		flag = False
	else:
		first_number = int(first)

	second = input("The second number is:")
	try:
		second_number = int(second)
	except ValueError:
		print("The input should be a number!")
		flag = False
	else:
		second_number = int(second)

	if flag:
		print(first_number + second_number)

	quit = input("Do you want to add again(y or n)?")

	if quit == "n":
		break

输出结果:

The first number is:2
The second number is:3
5
Do you want to add again(y or n)?y
The first number is:2
The second number is:a
The input should be a number!
Do you want to add again(y or n)?y
The first number is:a
The input should be a number!
The second number is:2
Do you want to add again(y or n)?n

10-12

代码:

import json

filename = 'number.json'

number = ""

try:
	with open(filename) as f_obj:
		number = json.load(f_obj)
except FileNotFoundError:
	number = input("What is you favorite number:")
	with open(filename,'w') as file:
		json.dump(number,file)
		print("I have remmember your favorite number!")
else:
	print("I know your favorite number!It's " + number +".")

第一次输出结果:

What is you favorite number:5
I have remmember your favorite number!

第二次输出结果:

I know your favorite number!It's 5.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值