[第五周]第十章课后习题

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

learning_python.txt:

In Python you can make a small game!
In Python you can do data analysis!
In Python you can make your own website!

代码:

#读取整个文件
with open('learning_python.txt') as file_object:
    contents=file_object.read()
print(contents)
print('\n\n')

#遍历文件对象
with open('learning_python.txt') as file_object:    
    for line in file_object:
        print(line)
print('\n\n')

#各行存储在列表中
with open('learning_python.txt') as file_object:
    content=file_object.readlines()
for line in content:
    print(line)

输出:

In Python you can make a small game!
In Python you can do data analysis!
In Python you can make your own website!



In Python you can make a small game!

In Python you can do data analysis!

In Python you can make your own website!



In Python you can make a small game!

In Python you can do data analysis!

In Python you can make your own website!

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

name=input('Please enter your name:\n')
with open('guest.txt','w') as file_object:
    file_object.write(name)

执行完成后,生成guest.txt:

Eric

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

num1=input('Enter 1st number:\n')
num2=input('Enter 2nd number:\n')
try:
    num1=int(num1)
    num2=int(num2)
except ValueError:
    print('The number you input is a not number!')
else:
    print(num1+num2)

输出1:

Enter 1st number:
2
Enter 2nd number:
3
5

输出2:

Enter 1st number:
a
Enter 2nd number:
2
The number you input is not a number!

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

第一个文件:

import json
number=input('Please input a number you like:\n')
with open('number.json','w') as file_object:
    json.dump(number,file_object)

第二个文件:

import json
with open('number.json') as f_object:
    number=json.load(f_object)
    print("I know your favorite number! It's "+number)

输出:
第一个文件:

Please input a number you like:
9

第二个文件:

I know your favorite number! It's 9

猜你喜欢

转载自blog.csdn.net/shu_xi/article/details/79824939
今日推荐