• 《Python编程:从入门到实践》第十章练习题


    《Python编程:从入门到实践》第十章练习题

    10-1 Python学习笔记

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

    代码:

    file_name = 'learning_python.txt'
    
    print("\n--- Way 1 ---")
    with open(file_name) as file_object:
        contents = file_object.read()
        print(contents.rstrip())
    
    print("\n--- Way 2 ---")
    with open(file_name) as file_object:
        for line in file_object:
            print(line.rstrip())
    
    print("\n--- Way 3 ---")
    with open(file_name) as file_object:
        lines = file_object.readlines()
    for line in lines:
        print(line.rstrip())
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    learning_python.txt:

    In Python you can learn how to use array.
    In Python you can learn how to use adictionary.
    In Python you can learn how to use function.
    
    • 1
    • 2
    • 3

    10-2 C语言学习笔记

    可使用方法replace()将字符串中的特定单词都替换为另一个单词。
    下面是一个简单的示例,演示了如何将句子中的’dog’替换为’cat’:

    >>> message = "I really like dogs. "
    >>> print(message.replace(' dog' , ' cat' ))
    ' I really like cats. '
    
    • 1
    • 2
    • 3

    读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称, 如C。 将修改后的各行都打印到屏幕上。

    代码:

    file_name = 'learning_python.txt'
    
    with open(file_name) as file_object:
        lines = file_object.readlines()
    
    for line in lines:
        replace_line = line.replace('Python', 'C++')
        print(replace_line.rstrip())
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    learning_python.txt:

    In Python you can learn how to use array.
    In Python you can learn how to use adictionary.
    In Python you can learn how to use function.
    
    • 1
    • 2
    • 3

    10-3 访客

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

    代码:

    file_name = 'guest.txt'
    
    name = input("Please input your name: ")
    with open(file_name, 'a') as file_object:
        file_object.write(name + '\n')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    guest.txt:

    ZhangSan
    LiSi
    WangWu
    
    • 1
    • 2
    • 3

    10-4 访客名单

    编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。

    代码:

    import time
    
    
    file_name = 'guest_book.txt'
    prompt = "\nPlease input your name(Enter 'quit' to end the program): "
    
    while True:
        name = input(prompt)
        if name == 'quit':
            break
    
        print("\nHi, " + name + "! Nice to see you again!")
        log_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    
        with open(file_name, 'a') as file_object:
            file_object.write(name + " logged in in " + log_time + ".\n")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    guest_book.txt:

    ZhangSan logged in in 2022-09-05 18:58:42.
    LiSi logged in in 2022-09-05 18:58:48.
    
    • 1
    • 2

    10-5 关于编程的调查

    编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后, 都将其添加到一个存储所有原因的文件中。

    代码:

    file_name = 'reasons.txt'
    prompt = "\nPlease tell me why you love coding(Enter 'quit' to end the program): "
    
    while True:
        reason = input(prompt)
        if reason == 'quit':
            break
    
        with open(file_name, 'a') as file_object:
            file_object.write(reason + '\n')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    reason.txt:

    Coding is fun!
    Coding helps me to get a nice job.
    
    • 1
    • 2

    10-6 加法运算

    代码:

    print("Give me two numbers, and I will add them.")
    
    first_number = input("\nFirst number: ")
    second_number = input("Second number: ")
    
    try:
        answer = int(first_number) + int(second_number)
    except ValueError:
        print("\nError! Make sure you enter two digits.")
    else:
        print('\n' + first_number + ' + ' + second_number + ' = ' + str(answer))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    10-7 加法计算器

    将你为完成练习 10-6 而编写的代码放在一个 while 循环中,让 用户犯错(输入的是文本而不是数字)后能够继续输入数字。

    代码:

    print("Give me two numbers, and I will add them.")
    print("Enter 'quit' to end the program.")
    
    while True:
        first_number = input("\nFirst number: ")
        if first_number == 'quit':
            break
    
        second_number = input("Second number: ")
        if second_number == 'quit':
            break
    
        try:
            answer = int(first_number) + int(second_number)
        except ValueError:
            print("\nError! Make sure you enter two digits.")
        else:
            print('\n' + first_number + ' + ' + second_number + ' = ' + str(answer))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    10-8 猫和狗

    创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误, 并打印一条友好的消息。将其中一个文件移到另一个地方, 并确认except 代码块中的代码将正确地执行。

    代码:

    def print_file(filename):
        try:
            with open(filename) as file_object:
                lines = file_object.readlines()
        except FileNotFoundError:
            print("\nSorry, the file " + filename + " doesn't exist.")
        else:
            print("\nContents in file " + filename + ":")
            for line in lines:
                print("\t" + line.rstrip())
    
    
    file_names = ['cats.txt', 'dogs.txt']
    for file_name in file_names:
        print_file(file_name)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    cats.txt:

    Lucy
    Jack
    Amy
    
    • 1
    • 2
    • 3

    dogs.txt:

    ZhangSan
    LiSi
    WangWu
    
    • 1
    • 2
    • 3

    10-9 沉默的猫和狗

    修改你在练习10-8中编写的except代码块,让程序在文件不存在时一言不发。

    代码:

    def print_file(filename):
        try:
            with open(filename, 'r') as file_object:
                contents = file_object.read()
        except FileNotFoundError:
            pass
        else:
            print("\nContents in file " + filename + ":")
            print(contents)
    
    
    file_names = ['cats.txt', 'dogs.txt']
    for file_name in file_names:
        print_file(file_name)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    10-10 常见单词

    常见单词:访问项目Gutenberg(http://gutenberg.org/),并找一些你想分析的图书。 下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。

    你可以使用方法count()来确定特定的单词或短语在字符串中出现了多少次。 例如,下面的代码计算’row’在一个字符串中出现了多少次:

    >>> line = "Row, row, row your boat"
    >>> line.count('row')
    2 >
    >> line.lower().count('row')
    3 
    
    • 1
    • 2
    • 3
    • 4
    • 5

    请注意,通过使用lower()将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。

    编写一个程序,它读取你在项目Gntenberg中获取的文件,并计算单词"the"在每个文件中分别出现了多少次。

    代码:

    def count_word(filename, word):
        try:
            with open(filename, 'r', encoding='utf-8') as file_object:
                contents = file_object.read()
        except FileNotFoundError:
            print("\nSorry, the file " + filename[6:] + " doesn't exist.")
        else:
            count_of_word = contents.count(word)
            return count_of_word
    
    
    file_names = ["books/Alice's Adventures in Wonderland by Lewis Carroll.txt",
                  "books/The Masque of the Red Death by Edgar Allan Poe.txt",
                  "books/Pride and Prejudice by Jane Austen.txt"]
    keyword = 'the'
    
    for file_name in file_names:
        count = count_word(file_name, keyword)
        if count:
            message = "\nWord '" + keyword + "' appears " + str(count) + " times in " + file_name[6:-4] + "."
            print(message)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    books:

    在这里插入图片描述

    10-11 喜欢的数字

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

    代码:

    dump_favorite_number.py:

    import json
    
    
    filename = 'favorite_number.json'
    number = 6
    
    with open(filename, 'w') as file_object:
        json.dump(number, file_object)
        print("We'll remember that " + str(number) + " is your favorite number.")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    load_favorite_number.py:

    import json
    
    
    filename = 'favorite_number.json'
    
    with open(filename, 'r') as file_object:
        number = json.load(file_object)
    
    print("I know your favorite number! It's " + str(number) + ".")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    favorite_number.json:

    在这里插入图片描述

    10-12 记住喜欢的数字

    将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。

    代码:

    import json
    
    
    filename = 'my_favorite_number.json'
    
    try:
        with open(filename) as file_object:
            favoriteNumber = json.load(file_object)
    except FileNotFoundError:
        number = input("\nWhat's your favorite number? ")
        with open(filename, 'w') as file_object:
            json.dump(number, file_object)
            print("We'll remember that " + str(number) + " is your favorite number.")
    else:
        print("I know your favorite number! It's " + str(favoriteNumber) + ".")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    my_favorite_number.json:

    在这里插入图片描述

    10-13 验证用户

    最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形: 当前和最后一次运行该程序的用户并非同一个人。

    为此,在greet_user()中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username()让用户输入正确的用户名。

    代码:

    import json
    
    
    def get_stored_username():
        filename = 'username.json'
        try:
            with open(filename, 'r') as file_object:
                username = json.load(file_object)
        except FileNotFoundError:
            return None
        else:
            return username
    
    
    def get_new_username():
        filename = 'username.json'
        username = input("What's your name? ")
    
        with open(filename, 'w') as file_object:
            json.dump(username, file_object)
    
        return username
    
    
    def greet_user():
        username = get_stored_username()
        if username:
            check = input("Is " + username + " your name? (yes/no): ")
            if check == 'yes':
                print("Welcome back, " + username + "!")
            else:
                username = get_new_username()
                print("We'll remember you when you come back, " + username + "!")
        else:
            username = get_new_username()
            print("We'll remember you when you come back, " + username + "!")
    
    
    greet_user()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    username.json:

    在这里插入图片描述

  • 相关阅读:
    CorelDRAW 2023全新版矢量图形制作工具
    C语言技术, 有云控经验最好
    【面试题】Ajax
    MySQL 事务隔离级别和MVCC版本控制
    多模态信息用于推荐系统问题(PMGT,MM-Rec,MGAT,TransRec)
    开发者实践|如何实现云开发场景联动(内附结构图和教学视频)
    C/C++内存管理
    设计模式-迭代器模式-笔记
    【算法优选】 滑动窗口专题——壹
    【MySQL系列】MySQL的用户管理
  • 原文地址:https://blog.csdn.net/ProgramNovice/article/details/126721295