Chapter10/11(文件和异常/测试代码)

2024-03-05 11:58

本文主要是介绍Chapter10/11(文件和异常/测试代码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

#10-1 Python学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。
# 将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,
# 并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
####读取整个文件####
with open('learning_python.txt') as file_object:contents=file_object.read()print(contents)
print("--------------------------")
#####遍历文件对象#####
with open('learning_python.txt') as file_object:for content in file_object:print(content.strip())
print("--------------------------")
#####将各行存储在一个列表中#####
with open('learning_python.txt') as file_object:lines=file_object.readlines()for line in lines:print(line.strip())
#结果
In Python you can learn English
In Python you can grab data
In Python you can build web
--------------------------
In Python you can learn English
In Python you can grab data
In Python you can build web
--------------------------
In Python you can learn English
In Python you can grab data
In Python you can build web
#10-2 C语言学习笔记 :可使用方法replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,
# 演示了如何将句子中的'dog' 替换为'cat' :
# >>> message = "I really like dogs."
# >>> message.replace('dog', 'cat')
#'I really like cats.'
# 读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。
with open('learning_python.txt') as file_object:lines=file_object.readlines()for line in lines:line=line.replace('Python','C')print(line.strip())
#结果
In C you can learn English
In C you can grab data
In C you can build web
#10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt
names=input("Enter your name: ")
with open('guest.txt','w') as file_object:file_object.write(names)
#结果
Enter your name: haly
############guest.txt###########
haly
# 10-4 访客名单 :编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,
# 并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
while True:names = input("Enter your name: ")print("How are you, "+names)with open('guest.txt', 'a') as file_object:file_object.write(names+'\n')
#结果
Enter your name: Helen
How are you, Helen
Enter your name: Angela
How are you, Angela
Enter your name: 
############guest.txt###########
haly
Helen
Angela
#10-5 关于编程的调查 :编写一个while 循环,询问用户为何喜欢编程。
# 每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
while True:reason = input("Why you so like programming? ")with open('reasons.txt', 'a') as file_object:file_object.write(reason+'\n')
#结果
Why you so like programming? Becaunse I love it
Becaunse I love it
Why you so like programming? No reason
No reason
Why you so like programming? Just to play
Just to play
Why you so like programming? 
############reasons.txt###########
Becaunse I love it
No reason
Just to play

依赖于try代码块成功执行的代码都应放到else代码块中

Python有一个pass 语句,可在except 代码块中使用它来让Python 什么都不要做

#10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,
# 将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,
#并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字.
while True:"""加法运算 """try:num1 = int(input("Enter first number: "))num2 = int(input("Enter second number: "))sum = num1 + num2except ValueError:print("please enter numbers rather than words")else:print("the sum is "+str(sum))#结果
Enter first number: 5
Enter second number: 7
the sum is 12
Enter first number: 8
Enter second number: lalaland
please enter numbers rather than words
Enter first number: 
#10-8 猫和狗 :创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。
# 编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,
# 并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行。
def readfile(filename):"""读取文件"""try:with open(filename) as file_object:contents=file_object.read()except FileNotFoundError:print("the file doesn't exits")else:print("the cats include:\n"+contents)
readfile("cats")
readfile("dogs")
#结果
the cats include:
HelloKitty
JiaFei
BuOu
the cats include:
WangCai
XiaoHey
XiaoHuang
#10-9 沉默的猫和狗 :修改你在练习10-8中编写的except 代码块,让程序在文件不存在时一言不发。
def readfile(filename):"""读取文件"""try:with open(filename) as file_object:contents=file_object.read()except FileNotFoundError:passelse:print("the cats include:\n"+contents)
readfile("cats")
readfile("birds")
readfile("dogs")
readfile("fishes")
#结果
the cats include:
HelloKitty
JiaFei
BuOu
the cats include:
WangCai
XiaoHey
XiaoHuang
# 10-10 常见单词:访问项目Gutenberg(http://gutenberg.org/ ),并找一些你想分析的图书。
# 下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。
# 你可以使用方法count() 来确定特定的单词或短语在字符串中出现了多少次。
# 例如,下面的代码计算'row'在一个字符串中出现了多少次:
# >>> line = "Row, row, row your boat"
# >>> line.count('row')
# 2
# >>> line.lower().count('row')
# 3
with open("paper") as file_object:contents=file_object.read()
print(contents.count("it"))
print(contents.lower().count("it"))
#结果
6
7
#10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。
#再编写一个程序,从文件中读取这个值,并打印消息“I knowyour favorite number! It's _____.”。
####first_json####
import json
filename = 'number.json'
number=input("please enter your favorite number: ")
with open(filename,'w') as f_obj:json.dump(number,f_obj)
####second_json####
import json
filename = 'number.json'
with open(filename) as f_obj:numbers=json.load(f_obj)print("I know your favorite number! It's "+numbers)
#结果####first_json####
please enter your favorite number: 8
####second_json####
I know your favorite number! It's 8
#10-12 记住喜欢的数字 :将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,
# 否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作
import json
filename = 'number.json'
try:with open(filename) as f_obj:number=json.load(f_obj)
except FileNotFoundError:number=input("please enter your favorite number: ")with open(filename,'w') as f_obj:json.dump(number,f_obj)
else:print("I know your favorite number! It's "+number)
#结果
I know your favorite number! It's 8
#10-13 验证用户 :最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。
# 我们应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个人。
# 为此,在greet_user() 中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username() 让用户输入正确的用户名。
import json
def get_stored_username():"""如果存储了用户名,就获取它"""filename = 'usernames.json'try:with open(filename) as f_obj:username = json.load(f_obj)except FileNotFoundError:return Noneelse:return username
def get_new_username():"""提示用户输入用户名"""username = input("What is your name? ")filename = 'usernames.json'with open(filename, 'w') as f_obj:json.dump(username, f_obj)return username
def greet_user():"""问候用户,并指出其名字"""username = get_stored_username()if username:answer = input("is your name "+username+" right? "+"  response:(yes or no)")if answer=='yes':print("Welcome back, " + username + "!")else:newname=get_new_username()print("We'll remember you when you come back, " + newname + "!")else:username = get_new_username()print("We'll remember you when you come back, " + username + "!")
greet_user()
#结果
What is your name? Selina
We'll remember you when you come back, Selina!
--------------------------------------------------
is your name selina right?   response:(yes or no)yes
Welcome back, selina!
--------------------------------------------------
is your name selina right?   response:(yes or no)  no
What is your name? helen
We'll remember you when you come back, helen!

方法名必须以test_打头,这样它才会在继承于unittest.TestCase的类中自动运行

#11-1 城市和国家 :编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为City, Country 的字符串,如Santiago, Chile 。
# 将这个函数存储在一个名为city_functions.py的模块中。创建一个名为test_cities.py的程序,对刚编写的函数进行测试
# (别忘了,你需要导入模块unittest 以及要测试的函数)。编写一个名为test_city_country() 的方法,
# 核实使用类似于'santiago' 和'chile' 这样的值来调用前述函数时,得到的字符串是正确的。运行test_cities.py ,确认测试test_city_country() 通过了。
##############city_functions.py##################
def city_country(City,Country):return City.title()+","+Country.title()
##############test_cities.py的程序################
import unittest
from printing_functions import city_country
class NameTestCase(unittest.TestCase):"""测试printing_functions.py"""
def test_city_country(self):formatted_name=city_country('shanghai','china')self.assertEqual(formatted_name,'Shanghai,China')
unittest.main()#结果
.
----------------------------------------------------------------------
Ran 1 tests in 0.001sOK
#11-2 人口数量 :修改前面的函数,使其包含第三个必不可少的形参population ,并返回一个格式为City, Country - population xxx 的字符串,
# 如Santiago, Chile - population 5000000 。运行test_cities.py,确认测试test_city_country() 未通过。
# 修改上述函数,将形参population 设置为可选的。再次运行test_cities.py,确认测试test_city_country() 又通过了。
# 再编写一个名为test_city_country_population() 的测试,核实可以使用类似于'santiago' 、'chile' 和'population=5000000' 这样的值来调用这个函数。
# 再次运行test_cities.py,确认测试test_city_country_population() 通过了.
##############city_functions.py#############
def city_country(city,country,population=''):if population:return city.title() + "," + country.title() + " - population " + populationelse:return city.title()+","+country.title()
##############tesy_city.py##################
import unittest
from printing_functions import city_country
class NameTestCase(unittest.TestCase):"""测试printing_functions.py"""def test_city_country(self):formatted_name=city_country('shanghai','china')self.assertEqual(formatted_name,'Shanghai,China')def test_city_country_population(self):formatted_name = city_country('Tokyo', 'Japan','500million')self.assertEqual(formatted_name, 'Tokyo,Japan - population 500million')
unittest.main()
#结果
..
----------------------------------------------------------------------
Ran 2 tests in 0.001sOK
#11-3 雇员:编写一个名为Employee 的类,其方法__init__() 接受名、姓和年薪,并将它们都存储在属性中。
# 编写一个名为give_raise() 的方法,它默认将年薪增加5000美元,但也能够接受其他的年薪增加量。
# 为Employee 编写一个测试用例,其中包含两个测试方法:test_give_default_raise() 和test_give_custom_raise() 。使用方法setUp() ,以免在
# 每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了
class Employee():def __init__(self,first,last,salary):self.first=firstself.last=lastself.salary=salarydef give_raise(self,add=5000):self.salary+=addreturn self.salary
import unittest
class NameTestCase(unittest.TestCase):def setUp(self):self.employee=Employee("Helen","Wang",6000)def test_give_default_raise(self):sala=str(self.employee.give_raise())self.assertEqual(sala, '11000')def test_give_custom_raise(self):sal=str(self.employee.give_raise(2000))self.assertEqual(sal,'8000')
unittest.main()
#结果
..
----------------------------------------------------------------------
Ran 2 tests in 0.000sOK

 

这篇关于Chapter10/11(文件和异常/测试代码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/776429

相关文章

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

C#文件复制异常:"未能找到文件"的解决方案与预防措施

《C#文件复制异常:未能找到文件的解决方案与预防措施》在C#开发中,文件操作是基础中的基础,但有时最基础的File.Copy()方法也会抛出令人困惑的异常,当targetFilePath设置为D:2... 目录一个看似简单的文件操作问题问题重现与错误分析错误代码示例错误信息根本原因分析全面解决方案1. 确保

Java利用@SneakyThrows注解提升异常处理效率详解

《Java利用@SneakyThrows注解提升异常处理效率详解》这篇文章将深度剖析@SneakyThrows的原理,用法,适用场景以及隐藏的陷阱,看看它如何让Java异常处理效率飙升50%,感兴趣的... 目录前言一、检查型异常的“诅咒”:为什么Java开发者讨厌它1.1 检查型异常的痛点1.2 为什么说

Java异常捕获及处理方式详解

《Java异常捕获及处理方式详解》异常处理是Java编程中非常重要的一部分,它允许我们在程序运行时捕获并处理错误或不预期的行为,而不是让程序直接崩溃,本文将介绍Java中如何捕获异常,以及常用的异常处... 目录前言什么是异常?Java异常的基本语法解释:1. 捕获异常并处理示例1:捕获并处理单个异常解释:

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束