python学习笔记:python基础知识100题

[复制链接]
查看1210 | 回复0 | 2024-3-10 07:34:48 | 显示全部楼层 |阅读模式

登录网站,浏览更多精彩内容

您需要 登录 才可以下载或查看,没有账号?加入我们

×
本帖最后由 前方录 于 2024-3-10 08:14 编辑

050、多分隔符单词计数


[mw_shl_code=python,false]string_list = re.split(r",| ", string)[/mw_shl_code]



060 字典变JSON
[mw_shl_code=python,false]
import json

d = {"employees": [{"firstName": "John", "lastName": "Doe"},
                   {"firstName": "Anna", "lastName": "Smith"},
                   {"firstName": "Peter", "lastName": "Jones"}],
     "owners": [{"firstName": "Jack", "lastName": "Petter"},
                {"firstName": "Jessy", "lastName": "Petter"}]}
with open("p060.json", "w") as f:
    f.write(json.dumps(d, indent=2))
[/mw_shl_code]


061 JSON变字典



[mw_shl_code=python,false]import json
import pprint

with open("p060.json") as f:
    d = json.loads(f.read())

pprint.pprint(d)[/mw_shl_code]

062 JSON添加数据

[mw_shl_code=python,false]import json

with open("p060.json") as f:
    d = json.loads(f.read())

d["employees"].append({'firstName': 'Albert', 'lastName': 'Bert'})

with open("p062.json", "w") as f:
    f.write(json.dumps(d, indent=2))
[/mw_shl_code]


064 定时打印

[mw_shl_code=python,false]import time

while True:
    print("Hello")
    time.sleep(2)[/mw_shl_code]

070 英汉翻译异常处理

[mw_shl_code=python,false]d = {"apple": "苹果", "orange": "桔子", "banana": "香蕉"}

def translate(word):
    try:
        return d[word]
    except KeyError:
        return "单词不在词典中"

word = input("Enter word: ")
print(translate(word))[/mw_shl_code]


071 英汉翻译文件词典

[mw_shl_code=html,false]p071.txt文件内容:
apple,苹果
orange,桔子
banana,香蕉
pear,梨
peach,桃
grape,葡萄
lemon,柠檬[/mw_shl_code]



[mw_shl_code=python,false]engdict = {}
with open("p071.txt", encoding="utf8") as f:
  for line in f:
    eng, ch = line.strip().split(",")
    engdict[eng] = ch

def translate(word):
  try:
    return engdict[word]
  except KeyError:
    return "单词不在词典中"


word = input("Enter word: ").lower()
print(translate(word))[/mw_shl_code]


072 当前日期时间


[mw_shl_code=python,false]from datetime import datetime

print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))[/mw_shl_code]



073 输入年龄计算出生年


[mw_shl_code=python,false]from datetime import datetime

age = int(input("请输入年龄:"))
year_birth = datetime.now().year - age
print(f"你的出生年份是:{year_birth}")[/mw_shl_code]


074 计算活了多少天

[mw_shl_code=python,false]import datetime

birthday = input("请输入生日:")
birthday_date = datetime.datetime.strptime(birthday, "%Y-%m-%d")

curr_datetime = datetime.datetime.now()

minus_datetime = curr_datetime - birthday_date

print(minus_datetime.days, "天")[/mw_shl_code]


075 计算今天明天昨天的日期

[mw_shl_code=python,false]import datetime

def diff_days(days):
    pdate_obj = datetime.datetime.now()
    time_gap = datetime.timedelta(days=days)
    pdate_result = pdate_obj - time_gap
    return pdate_result.strftime("%Y-%m-%d")

print(diff_days(0), diff_days(1), diff_days(-1), diff_days(7))[/mw_shl_code]



076 输出间隔内的所有日期




[mw_shl_code=python,false]import datetime

def get_date_range(begin_date, end_date):
    date_list = []
    while begin_date <= end_date:
        date_list.append(begin_date)
        begin_date_object = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
        days1_timedelta = datetime.timedelta(days=1)
        begin_date = (begin_date_object + days1_timedelta).strftime("%Y-%m-%d")
    return date_list

begin_date = "2022-05-14"
end_date = "2022-05-18"
date_list = get_date_range(begin_date, end_date)
print(date_list)[/mw_shl_code]


077 用户名检测器


[mw_shl_code=html,false]p077_users.txt文件内容如下:
xiaoming
xiaowang
xiaozhang
xiaozhao
xiaoqian
xiaosun[/mw_shl_code]


[mw_shl_code=python,false]while True:
    username = input("请输入用户名:")
    with open("p077_users.txt") as f:
        users = [name.strip() for name in f.readlines()]

    if len(username) < 6:
        print("长度小于6位,请重新输入")
        continue

    if username in users:
        print("用户名已存在,请重新输入")
        continue
    else:
        print("用户名检测通过")
        break[/mw_shl_code]


078 随机密码生成器


[mw_shl_code=python,false]import string
import random

words = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation

len = int(input("请输入密码位数:"))
chosen = random.sample(words, len)
password = "".join(chosen)
print(password)[/mw_shl_code]


079 密码强度检测器



编写Python代码,需要用户一直输入密码,直到满足如下条件才退出循环:
至少包含一个数字;
至少包含一个大写字母;
密码至少6位数;


[mw_shl_code=python,false]while True:
    pwd = input("请输入密码: ")
    have_number = any([i.isdigit() for i in pwd])
    have_upper = any([i.isupper() for i in pwd])

    if have_number and have_upper and len(pwd) >= 6:
        print("密码校验通过")
        break
    else:
        print("密码校验不通过,请重新输入")[/mw_shl_code]


080 详细错误密码检测器


[mw_shl_code=html,false]编写Python代码,需要用户一直输入密码,直到满足如下条件才退出循环:
至少包含一个数字;
至少包含一个大写字母;
密码至少6位数;[/mw_shl_code]


[mw_shl_code=python,false]while True:
    msgs = []
    psw = input("请输入密码: ")
    if not any([i.isdigit() for i in psw]):
        msgs.append("需要至少一位数字")
    if not any([i.isupper() for i in psw]):
        msgs.append("需要至少一位大写字母")
    if len(psw) < 6:
        msgs.append("需要至少6位密码")
    if len(msgs) == 0:
        print("密码检测通过")
        break
    else:
        print("密码不通过,有如下原因: ")
        for note in msgs:
            print("*", note)
[/mw_shl_code]


















中国领先的数字技术资源交流中心!

30

主题

9

回帖

254

积分

学徒

积分
254
学费
200