首页 > 编程知识 正文

Python第五章课后编程题用法介绍

时间:2023-11-20 16:12:23 阅读:289705 作者:MTTJ

在这篇文章中,我们将对Python第五章课后编程题进行详细的阐述。我们将从多个方面去了解这些编程题,包括题目的解释、程序代码及其解释等内容。希望这篇文章能够对你进一步了解Python的编程能力有所帮助。

一、密码检查程序

这个编程题要求我们编写一个密码检查程序。程序需要验证用户输入的密码是否符合规则。密码需要满足以下条件:

1.密码长度不少于8个字符

2.密码必须包含大写字母、小写字母、数字和特殊字符(例如:#,@,!等)

需要注意的是:

1. 需要使用正则表达式进行密码匹配

2. 如果密码符合规则,则打印“密码强度合格”,否则打印相应的警告信息。

import re

def password_check(password):
    if len(password) < 8:
        print("密码强度不合格:密码长度不足8位!")
        return False
    elif not re.search('[a-z]', password):
        print("密码强度不合格:密码需要包含小写字母!")
        return False
    elif not re.search('[A-Z]', password):
        print("密码强度不合格:密码需要包含大写字母!")
        return False
    elif not re.search('[0-9]', password):
        print("密码强度不合格:密码需要包含数字!")
        return False
    elif not re.search('[#$@!]', password):
        print("密码强度不合格:密码需要包含特殊字符!")
        return False
    else:
        print("密码强度合格!")
        return True

password_check("P@ssw0rd")  # 输出密码强度合格
password_check("password1!")  # 输出密码强度合格
password_check("pass1")  # 输出密码强度不合格:密码长度不足8位!
password_check("Passwor")  # 输出密码强度不合格:密码需要包含小写字母!
password_check("PASSWORD")  # 输出密码强度不合格:密码需要包含小写字母!
password_check("12345678")  # 输出密码强度不合格:密码需要包含小写字母!
password_check("!#@$%^&*")  # 输出密码强度不合格:密码需要包含小写字母!

二、石头、剪子、布游戏

这个编程题要求我们通过程序来实现石头、剪子、布游戏。具体地说,程序会询问用户出拳的情况,然后通过随机数来决定电脑出拳。最后,判断输赢情况,并显示相关的信息。

需要注意的是:

1. 采用循环实现多轮游戏的体验

2. 游戏在不同轮次中不断变化,应采用函数对不同的轮次进行处理

import random

def get_user_choice():
    while True:
        user_choice = input("请出拳(石头[1],剪子[2],布[3]):")
        if not user_choice.isnumeric():
            print("你输入的不是数字,请重新输入!")
            continue
        user_choice = int(user_choice)
        if user_choice not in [1, 2, 3]:
            print("你输入的不是有效数字,请重新输入!")
            continue

        return user_choice


def get_computer_choice():
    return random.randint(1, 3)


def game_over(user_choice, computer_choice):
    if (user_choice == 1 and computer_choice == 2) or 
            (user_choice == 2 and computer_choice == 3) or 
            (user_choice == 3 and computer_choice == 1):
        return True
    else:
        return False


def show_result(is_win):
    if is_win:
        print("恭喜您,您赢了!")
    else:
        print("很遗憾,您输了!")


def game():
    total_times = 0
    win_times = 0
    while True:        
        total_times += 1
        user_choice = get_user_choice()
        computer_choice = get_computer_choice()
        if user_choice == computer_choice:
            print("平局,再来一次!")
        elif game_over(user_choice, computer_choice):
            win_times += 1            
            show_result(True)
        else:
            show_result(False)
        if input("是否继续游戏?(是[1],否[0]):") != '1':
            break
    print("总共玩了{0}次,赢了{1}次,胜率为{2:.2f}%。".format(total_times, win_times, win_times / total_times * 100))


game()

三、猜数字游戏

这个编程题要求我们编写一个猜数字游戏的程序。程序会在[1, 100]中随机生成一个整数,用户通过输入数字来猜测这个整数。如果猜错,则会提示用户游戏还需要再次尝试。如果猜中则恭喜用户,并告知用户猜测的次数。

import random

def guess_number():
    target = random.randint(1, 100)
    user_input = None
    times = 0
    while user_input != target:
        user_input = int(input("请输入一个1到100之间的整数:"))
        times += 1
        if user_input > target:
            print("猜大了,请重试。")
        elif user_input < target:
            print("猜小了,请重试。")
        else:
            print("恭喜你,猜中了!共猜测了{0}次。".format(times))

guess_number()

四、单词计数器

这个编程题要求我们编写一个程序来计算一段文本中单词的数量。程序需要实现以下功能:

1. 统计单词的数量,并将结果输出到控制台

2. 将单词数量输出到文件中

需要注意的是:

1. 需要对单词进行分割和去重操作

2. 输出结果时需要考虑结果格式和排版

3. 输出到文件的文件名可以自由命名

import string

def count_words(txt):
    words = txt.split()
    words = [word.strip(string.punctuation) for word in words]
    words = [word.lower() for word in words]
    words = set(words)
    word_count = {word: words.count(word) for word in words}
    return word_count


def print_result(word_count):
    count_order = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
    for key, value in count_order:
        print("{0:<15}-{1:>5}".format(key, value))


def save_result(word_count, file_name):
    count_order = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
    with open(file_name, 'w') as file:
        file.write("{0:<15}{1:>5}n".format("单词数量", "出现次数"))
        file.write("==================n")
        for key, value in count_order:
            file.write("{0:<15}-{1:>5}n".format(key, value))


txt = """
Life is like a box of chocolates, you never know what you're gonna get.
Sometimes, I guess there's just not enough rocks.
Life is a journey and only you hold the key.
You never have to take back words you don't speak.
"""
result = count_words(txt)
print_result(result)
save_result(result, "word_count.txt")

五、斐波那契数列

这个编程题要求我们编写程序来计算斐波那契数列。斐波那契数列的值是每个数字的和,这个数字等于前面两个数字之和。

def fibonacci(n):
    if n <= 0:
        return []
    elif n == 1:
        return [1]
    elif n == 2:
        return [1, 1]
    else:
        fib = [1, 1]
        for i in range(2, n):
            fib.append(fib[i-1] + fib[i-2])
        return fib

print(fibonacci(0)) # output: []
print(fibonacci(1)) # output: [1]
print(fibonacci(2)) # output: [1, 1]
print(fibonacci(5)) # output: [1, 1, 2, 3, 5]
print(fibonacci(10)) # output: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

六、总结

Python第五章课后编程题的内容涉及到了正则表达式、随机数、循环以及函数等知识点,通过这些题目的学习,我们可以更好地掌握Python的编程能力。希望本文的介绍能让你更好的理解Python编程。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。