99.Python 基础练习题
大约 2 分钟学习笔记Python基础基础练习
练习题 1
题目要求
有一个数据 list of dict 如下 a = [{"test1": "123456"},{"test2": "123456"},{"test3": "123456"}]
写入到本地一个 txt 文件,内容格式如下: test1,123456 test2,123456 test3,123456
案例源码
a = [{"test1": "123456"},{"test2": "123456"},{"test3": "123456"}]
def write_txt():
    with open("test1.txt", "w+", encoding="utf8") as f:
        for data in a:
            for key, value in data.items():
                d = f"{key},{value}\n"
                f.write(d)
write_txt()练习题 2
题目要求
a = [1, 2, 3, 4, 5] b = ["a", "b", "c", "d", "e"] 如何得出 c = ["a1", "b2", "c3", "d4", "e5"]
案例源码
a = [1, 2, 3, 4, 5]
b = ["a", "b", "c", "d", "e"]
c = []
if len(a) == len(b):
    for i in range(len(b)):
        c.append(f"{str(b[i]) + str(a[i])}")
print(c)练习题 3
题目要求
写一个小程序:控制台输入邮箱地址(格式为 username@companyname.com), 程序识别用户名和公司名后,将用户名和公司名输出到控制台。 要求:
- 校验输入内容是否符合规范(xx@polo.com), 如是进入下一步,如否则抛出提 示"incorrect email format"。注意必须以.com 结尾
- 可以循环“输入--输出判断结果”这整个过程
- 按字母 Q(不区分大小写)退出循环,结束程序
案例源码
while True:
    input_str = input(f"请输入邮箱: ")
    if input_str.upper() == "Q":
        break
    if input_str.endswith(".com") and "@" in input_str:
        data = input_str.split('.com')[0].split('@')
        user_name = data[0]
        company_name = data[1]
        print(f"userName: {user_name}, companyName: {company_name}")
        break
    else:
        print(f"邮箱格式错误, 请重新输入")练习题 4
题目要求
如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。
 例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一个水仙花数 那么问题来了,求 1000 以内的水仙花数(3 位数)
案例源码
lists = []
for num in range(100, 1000):
    num = str(num)
    n1, n2, n3 = int(num[0]), int(num[1]), int(num[2])
    if n1 ** 3 + n2 ** 3 + n3 ** 3 == int(num):
        lists.append(num)
print(lists)