超实用Python小项目

编程 · 2023-08-01 · 262 人浏览

通过查表确定星座

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}")
Python
Theme Jasmine by Kent Liao