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

相关文章

Docker启动异常

报错信息: failed to start daemon: Error initializing network controller: error creating default "bridge" network: cannot create network b8fd8c684f0ba865d4a13d36e5282fd694bbd37b243c7ec6c9cd29416db98d4b (d

已解决javax.management.BadStringOperationException异常的正确解决方法,亲测有效!!!

已解决javax.management.BadStringOperationException异常的正确解决方法,亲测有效!!! 目录 问题分析 出现问题的场景 报错原因 解决思路 解决方法 分析错误日志 检查字符串值合法性 确认字符串格式 优化代码逻辑 增加输入验证和错误处理 总结 博主v:XiaoMing_Java 问题分析 javax.manag

java编程:命令行输入的三个整数判断是否构成三角形,不能就抛异常。

写一个方法void sanjiao(int a,int b,int c),判断三个参数是否能构成一个三角形,如果不能则抛出 异常IllegalArgumentException,显示异常信息“a,b,c不能构成三角形”, 如果可以构成则显示三角形三个边长,在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。 附源代码: package 异常;public class Sa

MapReduce 实践题:Web 访问日志分析与异常检测

文章目录 作业描述MapReduce 实践题:Web 访问日志分析与异常检测题目背景数据集说明任务要求输入数据示例输出数据示例实现步骤 解题思路1. 数据预处理2. 访问统计3. 异常检测4. 主方法5. 结果输出 作业描述 MapReduce 实践题:Web 访问日志分析与异常检测 题目背景 你被要求设计和实现一个基于 MapReduce 的大规模 Web 访问日志分析

异常处理的解决方案

package 异常;/** A:一个异常* B:二个异常的处理* a:每一个写一个try...catch* b:写一个try,多个catch* try{* ...* }catch(异常类名 变量名) {* ...* }* catch(异常类名 变量名) {* ...* }* ...* * 注意事项:* 1:能明确

异常结构图、编译期异常和运行期异常的区别

异常处理一般有2种方式,要么捕获异常try-catch,要么抛出异常throws 如果一个方法后面抛出一个运行时期异常(throws RuntimeException),调用者无须处理 如果一个方法后面抛出一个编译时期异常,调用者必须处理,或者抛出或者try-catch; 运行时期的异常一般都不处理,一般是程序逻辑上的错误,比如分母为0作为除数了。。。 注意如果在try里面出现了异常后,

android开发异常信息收集程序代码

首先创建全局的Application ,此Application全局通用。 package com.demo.utils;import com.demo.exception.CrashHandler;import android.app.Application;/*** 全局的context,任意位置调用* @author Administrator**/public class Gl

IOS Swift 从入门到精通: 函数,参数和异常

文章目录 编写函数接受参数返回值参数标签省略参数标签默认参数可变参数函数编写抛出函数运行异常函数输入输出参数总结 编写函数 函数让我们可以重复使用代码,这意味着我们可以编写一个函数来做一些有趣的事情,然后从很多地方运行该函数。重复代码通常是一个坏主意,而函数可以帮助我们避免这样做。 首先,我们要编写一个函数来为应用用户打印帮助信息。我们可能在应用中的任何地方都需要它,因此将其作

SpringBoot (二) :全局异常处理设置

说在前面 在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中 说明 @ControllerAdvice 该注解是spring3.2以后新增的一个注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,