08 Store data

[TOC]

<span id="start">test function</span>

name_function.py

    def get_formatted_name(first,last):
        """Generate(生成) a neatly(整齐的) formatted full name."""
        full_name = first + ' ' + last
        return full_name.title()

names.py

    from name_function import get_formatted_name

    print("Enter 'q' at any time to qiut.")
    while True:
        first = input("\nPlease give me a first name: ")
        if first == 'q':
            break
        last = input("Please give me a last name: ")
        if last == 'q'
            break
        formatted_name = get_formatted_name(first,last)
        print("\tNeatly formatted name: "+ formatted_name + '.')

1.Unit testing and test cases.
The module <unittest> in the Python standard library provide code testing tools.Unit test are used to verify that there is no problem with some aspect of the function.A test case is a set of unit tests,these unit tests together verify that the function behaves in all cases.
2.Pass the test
test_name_function.py

    import unittest 
    from name_function import get_formatted_name

    class NamesTestCase(unittest.TestCase): # This class must inherit class unittest.TestCase.
        """test name_function.py"""

        def test_first_last_name(self):
            """Can you handle a name like Janis Joplin correctly?"""
            formatted_name = get_formatted_name('janis','joplin')
            self.assertEqual(formatted_name,'Janis Joplin')  

    unittest.main()

assertEqual function
Explanation:

First we import the module 'unittest' and the function 'get_formatted_name' to test.We created a class named NamesTestCase,you can name it any way you want,but it's best to make it look relevant to the function you're testing.This class must inherit class unittest.TestCase.
<span id="jump">assert</span> function:it use to verify whether the results were in line with the expected results.

The output from running test_name_function.py:

    .  
    ------------------------------------------------
    Ran 1 test in 0.000s

    OK

The period in the first line indicates a test passed

Test class

1.all kinds of assert
we have a lot of assert function in python.

assertEqual(a,b)-----------------verify a == b
assertNotEqual(a,b)--------------verify a != b
assertTrue(x)--------------------verify x is True
assertFalse(x)-------------------verify x is False
assertIn(item,list)--------------verify item in list
assertNotIn(item,list)-----------verify item not in list

[to be continued]

jump to head

import json

numbers = [1,2,3,4,5]

filename = 'numbers.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)#stroe date to file
Let's first import module json,then create a list of numbers.
The file extension **.json** is usually used to indicate that the file stores data in JSON format.
import json

filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)# use json.load() to load the information stored in numbers.json.
print(numbers)

2.Sava and read user-generated data
Store username:
import json
username = input("What is your name? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
    json.dump(username,f_obj)
    print("We'll remeber you wehn you come back, "+username+" !")
Read file data:
import json

filename = 'username.json'

with open(filename) as f_obj:
    username = json.load(f_obj)
    print("Welcome back, " + username + "!")
Now,we need to merge two programs into one program.When the program runtime,we will try to get the username from the file 'username.json'.So let's first write a 'try' code that tries to restore the username,If this file doesn't exist,we prompt the user for a username in the 'except' code block,and store in the file 'username,json'.
import json

# If the previously stored username is loaded
# Else prompt the user to enter the username an store it.
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except:
    username = input("What is your name? ")
    with open(filename,'w') as f_obj:
        json.jump(username,f_obj)
        print("We'll remember you when you come back, "+ username + "!")
else:
    print("Welcome back, "+username+"!")
3.reconstruction(重构)
You often encounter situations where the code works correctly and can be further improved---Divide the code into a series of functions that do the work.This process is called reconstruction.
import json

def greet_user():
    """greet the user and indicate their name"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        username = input("What is your name? ")
        with open(filename,'w') as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back, "+username+"!")
    else:
        print("Welcome back, "+username+"!")
greet_user()
reconstruction:
improt json

def get_stored_username():
    """if stored the username,load it"""
    try:
        filename = 'username.json'
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """prompt the user enters the username"""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename,'w') as f_obj:
        json.dump(username,f_obj)
    return username

def greet_user():
    """greet the user and divide their names"""
    username = get_stored_username()
    if username:
        print("Welcome back, "+username+"!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, "+username+"!")

greet_user()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352

推荐阅读更多精彩内容