第五周第二次作业

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

with open('learning_python.txt') as t1:
	tx = t1.read()
	print (tx.rstrip())
	
with open('learning_python.txt') as t2:
	for line in t2:
		print (line.rstrip())

lines = []
with open('learning_python.txt') as t3:
	for line in t3.readlines():
		lines.append(line)

[print(line.rstrip()) for line in lines]
结果
In Python you can read this text.
In Python you can calculate the sum of two number.
In Python you can make a computer game.
In Python you can read this text.
In Python you can calculate the sum of two number.
In Python you can make a computer game.
In Python you can read this text.
In Python you can calculate the sum of two number.
In Python you can make a computer game.


10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

mes = input('please enter tow numbers and I will calculate the sum of them:\n')
try:
	a, b = mes.split()
	a = int(a)
	b = int(b)
except ValueError:
	print ('please enter two truly numbers!')
else:
	print (a+b)
结果:
please enter tow numbers and I will calculate the sum of them:
c c
please enter two truly numbers!


10-11 喜欢的数字 :编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It's _____.”。

import json

a = input('enter your favorite numbers:\n')
with open('H10-11.json', 'w') as js:
	json.dump(a, js)
	
with open('H10-11.json') as js2:
	b = json.load(js2)
	
print ("I know your favorite number! It's " + b + '.')
结果:
enter your favorite numbers:
22
I know your favorite number! It's 22.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值