超实用Python小项目

228次阅读
没有评论

共计 6069 个字符,预计需要花费 16 分钟才能阅读完成。

判断字符串是否为回文串

while True:
    word = input("请输入一个单词:")
    if len(word) >= 3:
        break

i, j = 0, len(word) - 1
flag = True
while i <= j // 2:
    if word[i] != word[j]:
        flag = False
        break
        i += 1
        j -= 1

if flag:
    print(f"{word} 是回文串")
else:
    print(f"{word} 非回文串")

通过查表确定星座

import sys
from datetime import date

# 12/22-1/19 魔蝎座 1/20-2/18 水瓶座 2/19-3/20 双鱼座 3/21-4/19 白羊座 4/20-5/20 金牛座
# 5/21-6/21 双子座 6/22-7/22 巨蟹座 7/23-8/22 狮子座 8/23-9/22 处女座 9/23-10/23 天秤座
# 10/24-11/22 天蝎座 11/23-12/21 射手座
zodiac_name = ("摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座")
zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 20), (5, 21), (6, 22), (7, 23), (8, 23), (9, 23), (10, 24), (11, 23), (12, 22))

def is_valid_date(year, month, day):
    try:
        date(year, month, day)
    except ValueError:
        return False
    else:
        return True

try:
    month = int(input("请输入月份:"))
    day = int(input("请输入日期:"))

    if is_valid_date(date.today().year, month, day):
        for zd_num in range(12):
            if zodiac_days[zd_num] > (month, day):
                print("您的星座是 %s" % (zodiac_name[zd_num]))
                break
            elif month == 12 and (32 > day > 21):
                print("您的星座是 %s" % (zodiac_name[0]))
                break
    else:
        print("请输入正确的月份和日期")
        sys.exit()

except ValueError:
    print("请输入正确的月份和日期")

根据年份判断生肖

# 鼠 1,牛 2,虎 3,兔 4,龙 5,蛇 6,马 7,羊 8,猴 9,鸡 10,狗 11,猪 12
chinese_zodiac = "猴鸡狗猪鼠牛虎兔龙蛇马羊"

try:
    year = int(input("请输入年份:"))
    print("%s 年的生肖是 %s" % (year, chinese_zodiac[year % 12]))
except ValueError:
    print("年份要输入数字")

进度条

import random
import time

BAR = chr(9608)  # 9608 is '█'

def getProgressBar(progress, total, barWidth=40):
    """返回一个字符串,表示具有 barWidth 的进度条"""

    progressBar = "["

    # 确保 progress 在 0 ~ total 之间
    if progress > total:
        progress = total
    if progress < 0:
        progress = 0

    numberOfBars = int((progress / total) * barWidth)  # 计算需要多少个 █ 符号来显示进度
    progressBar += BAR * numberOfBars  # 添加进度条
    progressBar += " " * (barWidth - numberOfBars)  # 添加空白部分
    progressBar += "]"  # 添加右方括号

    percentComplete = round(progress / total * 100, 1)  # 计算百分比
    progressBar += "" + str(percentComplete) +"%"  # 添加百分比
    progressBar += "" + str(progress) +"/" + str(total)  # 添加已下载 / 总大小

    return progressBar

def main():
    bytesDownloaded = 0
    downloadSize = 4096
    while bytesDownloaded < downloadSize:
        bytesDownloaded += random.randint(0, 200)  # 随机下载 0~200 字节

        barStr = getProgressBar(bytesDownloaded, downloadSize)
        # flush = True 立即刷新输出缓冲区,确保能够立即看到输出,而不是等待缓冲区被刷新
        print(barStr, end="", flush=True)

        time.sleep(0.2)

        print("\b" * len(barStr), end="", flush=True)  # 打印退格符,使进度条回到行首

if __name__ == "__main__":
    main()

DNA 可视化

import random
import sys
import time

PAUSE = 0.15  # (!) Try changing this to 0.5 or 0.0.

# These are the individual rows of the DNA animation:
ROWS = [
    # 123456789 <- Use this to measure the number of spaces:
    "##",  # Index 0 has no {}.
    "#{}-{}#",
    "#{}---{}#",
    "#{}-----{}#",
    "#{}------{}#",
    "#{}------{}#",
    "#{}-----{}#",
    "#{}---{}#",
    "#{}-{}#",
    "##",  # Index 9 has no {}.
    "#{}-{}#",
    "#{}---{}#",
    "#{}-----{}#",
    "#{}------{}#",
    "#{}------{}#",
    "#{}-----{}#",
    "#{}---{}#",
    "#{}-{}#",
]
# 123456789 <- Use this to measure the number of spaces:

try:
    print("DNA Animation, by https://abee.ml")
    print("Press Ctrl-C to quit...")
    time.sleep(2)
    rowIndex = 0

    while True:  # Main program loop.
        # Increment rowIndex to draw next row:
        rowIndex = rowIndex + 1
        if rowIndex == len(ROWS):
            rowIndex = 0

        # Row indexes 0 and 9 don't have nucleotides:
        if rowIndex == 0 or rowIndex == 9:
            print(ROWS[rowIndex])
            continue

        # Select random nucleotide pairs, guanine-cytosine and
        # adenine-thymine:
        randomSelection = random.randint(1, 4)
        if randomSelection == 1:
            leftNucleotide, rightNucleotide = "A", "T"
        elif randomSelection == 2:
            leftNucleotide, rightNucleotide = "T", "A"
        elif randomSelection == 3:
            leftNucleotide, rightNucleotide = "C", "G"
        elif randomSelection == 4:
            leftNucleotide, rightNucleotide = "G", "C"

        # Print the row.
        print(ROWS[rowIndex].format(leftNucleotide, rightNucleotide))
        time.sleep(PAUSE)  # Add a slight pause.
except KeyboardInterrupt:
    sys.exit()  # When Ctrl-C is pressed, end the program.

超级秒表

import time

print('Press ENTER to begin. Afterward, press ENTER to"click"the stopwatch.Press Ctrl-C to quit.')
input()  # press Enter to begin
print("Started.")
startTime = time.time()  # get the first lap's start time
lastTime = startTime
lapNum = 1

try:
    while True:
        input()
        lapTime = round(time.time() - lastTime, 2)
        totalTime = round(time.time() - startTime, 2)
        print("Lap #%s: %s (%s)" % (lapNum, totalTime, lapTime), end="")
        lapNum += 1
        lastTime = time.time()  # reset the last lap time
except KeyboardInterrupt:
    # Handle the Ctrl-C exception to keep its error message from displaying.
    print("nDone.")

判断闰年

year = int(input("Which year do you want to check?"))

if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print('Leap year.')
        else:
            print('Not a leap year.')
    else:
        print('Leap year.')
else:
    print('Not a leap year.')

爱情计算器

print("Welcome to the Love Calculator!")
name1 = input("What is your name?n")
name2 = input("What is their name?n")
name = name1 + name2
name = name.lower()

t = name.count("t")
r = name.count("r")
u = name.count("u")
e = name.count("e")
score_true = t + r + u + e

l = name.count("l")
o = name.count("o")
v = name.count("v")
e = name.count("e")
score_love = l + o + v + e

score = score_true + score_love
print()
if score < 10 or score > 90:
    print(f"Your love score is {score}, you go together like coke and mentos.")
elif 40 < score < 50:
    print(f"Your love score is {score}, you are alright together.")
else:
    print(f"Your love score is {score}")

把 X 藏起来

row1 = ["⬜️", "⬜️", "⬜️"]
row2 = ["⬜️", "⬜️", "⬜️"]
row3 = ["⬜️", "⬜️", "⬜️"]
map = [row1, row2, row3]
print(f"{row1}n{row2}n{row3}")

## 23
position = input("Where do you want to put the treasure?n")
x = int(position[0])
y = int(position[1])
map[x - 1][y - 1] = "❌"
print(f"{row1}n{row2}n{row3}")

随机密码生成器

import random

letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
symbols = ["!", "#", "$", "%", "&", "(", ")", "*", "+"]

print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?n"))
nr_symbols = int(input("How many symbols would you like?n"))
nr_numbers = int(input("How many numbers would you like?n"))

password_list = []
password_list.extend(random.sample(letters, nr_letters))
password_list.extend(random.sample(symbols, nr_symbols))
password_list.extend(random.sample(numbers, nr_numbers))
random.shuffle(password_list)

password = "".join(password_list)
print(f"Here is your password: {password}")

绘制螺旋图

import random
import turtle

colors = ["red", "green", "blue", "pink", "yellow", "orange"]
t = turtle.Turtle()
t.speed(0)  # 设置速度为最快
turtle.bgcolor("black")
length = 100
angle = 50
size = 5
for i in range(length):
    color = random.choice(colors)
    t.pencolor(color)
    t.fillcolor(color)
    t.penup()
    t.forward(i + 50)
    t.pendown()
    t.left(angle)  # 初始方向朝右,对应角度为 0 度,逆时针方向为正方向

    t.begin_fill()
    t.circle(size)
    t.end_fill()

turtle.exitonclick()

正文完
 0
阿伯手记
版权声明:本站原创文章,由 阿伯手记 于2023-08-01发表,共计6069字。
转载说明:本站原创内容,除特殊说明外,均基于 CC BY-NC-SA 4.0 协议发布,转载须注明出处与链接。
评论(没有评论)
验证码

阿伯手记

阿伯手记
阿伯手记
喜欢编程,头发渐稀;成长路上,宝藏满地
文章数
766
评论数
204
阅读量
446488
今日一言
-「
热门文章
职场救急!AI请假话术生成器:1秒定制高通过率理由

职场救急!AI请假话术生成器:1秒定制高通过率理由

超级借口 不好开口?借口交给我!智能生成工作请假、上学请假、饭局爽约、约会拒绝、邀约推辞、万能借口等各种借口理...
夸克网盘快传助手提高非VIP下载速度

夸克网盘快传助手提高非VIP下载速度

夸克网盘限速这个大家都知道,不开会员差不多限速在几百 K。那有没有办法在合法合规途径加速下载夸克网盘呢?这里推...
国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

本文收集了目前国内已部署 DeepSeek 模型的第三方列表,个个都是免费不限次数的满血版 DeepSeek,...
巴别英语:用美剧和TED演讲轻松提升英语听力与口语

巴别英语:用美剧和TED演讲轻松提升英语听力与口语

还在为枯燥的英语学习而烦恼吗?巴别英语通过创新的美剧学习模式,让英语学习变得生动有趣。平台提供海量美剧和 TE...
Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 是一款在线中文姓名生成器,可在几秒内生成符合个人需求的中文名字。...
TVAPP:开源电视盒子资源库,一键打造家庭影院

TVAPP:开源电视盒子资源库,一键打造家庭影院

导语 TVAPP 是一个专为 Android TV 电视盒子用户打造的开源影音资源库,集成了影视、直播、游戏等...
2025年12月 每日精选

2025年12月 每日精选

关于每日精选栏目 发现一些不错的资源,点击 这里 快速投稿。 12 月 26 日 .ax 顶级域 目前全球唯一...
最新评论
15220202929 15220202929 怎么用
八对 八对 麻烦大佬更新下【堆新】的友链站名:八对星星描述:极目星视穹苍无界•足履行者大地有疆链接:https://8dui.com图标:https://cf.8dui.com/logo.webp横标:https://cf.8dui.com/logo-w.webp订阅:https://8dui.com/rss.xml
三毛笔记 三毛笔记 已添加
DUINEW DUINEW 已添加贵站,期待贵站友链~博客名称:堆新博客地址:https://duinew.com/博客描述:堆新堆新,引力向新!——堆新(DUINEW)博客头像:https://d.duinew.com/logo.webp横版头像:https://d.duinew.com/logo-w.webp博客订阅:https://duinew.com/rss.xml
hedp hedp 没看懂
bingo bingo 直接生成就可以啦,也可以添加一些选项
满心 满心 申请更新下友联信息,原名:满心记,现名:周天记原域名:qq.mba,现域名:zhoutian.com描述:我在人间混日子
开业吉日 开业吉日 没看明白这个怎么用
开业吉日 开业吉日 beddystories 这个网站太赞了,收藏
热评文章
夸克网盘快传助手提高非VIP下载速度

夸克网盘快传助手提高非VIP下载速度

夸克网盘限速这个大家都知道,不开会员差不多限速在几百 K。那有没有办法在合法合规途径加速下载夸克网盘呢?这里推...
清华大学官方免费DeepSeek教程

清华大学官方免费DeepSeek教程

AI 领域近期最引人注目的焦点当属 DeepSeek,这款由中国创新企业深度求索研发的人工智能工具,正以开放源...
Short-Link 免费开源短网址程序,基于Fastify、Vercel和Supabase构建

Short-Link 免费开源短网址程序,基于Fastify、Vercel和Supabase构建

Short-Link 是一款基于 Fastify、Vercel 和 Supabase 构建的 URL 缩短服务...
国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

本文收集了目前国内已部署 DeepSeek 模型的第三方列表,个个都是免费不限次数的满血版 DeepSeek,...
Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 是一款在线中文姓名生成器,可在几秒内生成符合个人需求的中文名字。...
BeddyStories 完全免费儿童睡前故事库,让孩子随时随地入睡更轻松

BeddyStories 完全免费儿童睡前故事库,让孩子随时随地入睡更轻松

BeddyStories 是一个致力于为儿童提供优质睡前故事的在线平台,用户可以在这里找到来自世界各地的经典故...
DrawLink:一键生成链接视觉卡片,提升分享点击率

DrawLink:一键生成链接视觉卡片,提升分享点击率

小贴士 :此站或已变迁,但探索不止步。我们已为您备好「类似网站」精选合集,相信其中的发现同样能为您带来惊喜。