10-1 Python学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为
learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个
发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一
消息“I know your favorite number! It's _____.”。
learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个
文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
with open("learning_python.txt") as lp:
print(lp.read())
with open("learning_python.txt") as lp:
for line in lp:
print(line)
with open("learning_python.txt") as lp:
for line in lp.readlines():
print(line.rstrip())
10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
filename = "guest.txt"
with open("guest.txt","a") as fw:
name = input("please write your name: ")
fw.write(name)
10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引
发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一
条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
while True:
try:
strx = input('please input the first number: ')
if(strx == 'q'):
break
numx = int(strx)
stry = input('please input the second number: ')
if(stry == 'q'):
break
numy = int(stry)
answer = numx + numy
except TypeError:
print('please input the number.')
except ValueError:
print('please input the number.')
else:
print(str(numx) + '+' + str(numy) + '=' + str(answer))
10-11 喜欢的数字 :编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印
消息“I know your favorite number! It's _____.”。
import json
filename = 'numbers.json'
#读取数字
numbers = input("please input your favorite number: ")
with open(filename,'w') as fw:
json.dump(numbers,fw)
#取出数字
with open(filename) as fr:
numbersx = json.load(fr)
print("I know your favorite number! It's " + numbersx + '.')