2018.4.4 Python作业
2018-04-07 18:55
288 查看
第十章 文件和异常10-1 Python学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至今学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with代码块外打印它们。with open('learning_python.txt') as fobj:
contents = fobj.read()
print(contents)
with open('learning_python.txt') as fobj:
for line in fobj:
print(line.rstrip())
with open('learning_python.txt') as fobj:
lines = fobj.readlines()
print(lines)10-3 访客:编写一个程序,提示用户输入其名字;用户做出相应后,将其名字写入到guests.txt中。name = input("Please enter your name:")
with open('guests.txt', 'w') as fobj:
fobj.write(name)10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。a = input("Please enter a number:")
b = input("Please enter a number:")
try:
x = float(a)+float(b)
print(x)
except ValueError:
msg = "Sorry, your input is not a number."
print(msg)10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.jump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It's _______”。#writefile.py
a = input("Please enter your favorite number:")
with open('number.txt', 'w') as fobj:
fobj.write(a)
contents = fobj.read()
print(contents)
with open('learning_python.txt') as fobj:
for line in fobj:
print(line.rstrip())
with open('learning_python.txt') as fobj:
lines = fobj.readlines()
print(lines)10-3 访客:编写一个程序,提示用户输入其名字;用户做出相应后,将其名字写入到guests.txt中。name = input("Please enter your name:")
with open('guests.txt', 'w') as fobj:
fobj.write(name)10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。a = input("Please enter a number:")
b = input("Please enter a number:")
try:
x = float(a)+float(b)
print(x)
except ValueError:
msg = "Sorry, your input is not a number."
print(msg)10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.jump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It's _______”。#writefile.py
a = input("Please enter your favorite number:")
with open('number.txt', 'w') as fobj:
fobj.write(a)
#readfile.py try: with open('number.txt') as fobj: number = fobj.read() print("I know your favorite number! It's " + number) except FileNotFoundError: msg = "Sorry, there is no such a file." print(msg)
相关文章推荐
- 作业1+2.四则运算(改进后完整版,用python写的)_064121陶源
- Python的第二次作业
- 有效使用Python来完成数论作业之同余式
- 第一周第一次作业——浏览Python主页后的发现和收获
- python 第一次作业
- Python第一次作业
- 零基础学习Python 作业 第10章
- python笔记及作业
- python自学-第八次作业
- python第二周作业 购物车
- Python自学-第12次作业
- 吴恩达deeplearning.ai课堂作业:Class 1 week2-Python+Basics+With+Numpy
- python作业之购物车
- 实验与作业(Python)-05 程序的控制结构
- Python第五周第一次作业
- Python 第二章练习题(第一周作业)
- 吴恩达机器学习编程作业python实现--ex1
- python作业(5)
- 第一周作业——浏览python网站的发现与收获和如果我成为python高手,我想写的程序
- python之ftp作业【还未完成】