Python生日快乐代码高级
时间: 2024-11-17 12:11:05 浏览: 125
当然,我们可以用Python编写一段有趣的代码来庆祝生日。这里我将演示如何使用`random`模块来创建一个随机选择祝福语的功能,然后用`datetime`模块获取当前日期并检查是否接近某个人的生日。如果今天是他们的生日,就输出特别的祝贺。
```python
import random
from datetime import date, timedelta
# 定义一个包含不同祝福语的列表
bday_wishes = [
"Happy Birthday!",
"Wishing you a fantastic day filled with joy!",
"May all your dreams come true on this special day!",
"You deserve the best year ever!",
]
def is_birthday(today, birth_date):
return today.replace(year=today.year) == birth_date
# 输入用户的姓名和生日(假设格式为 'YYYY-MM-DD')
name = input("Please enter your name: ")
birth_date_str = input(f"Enter your birthday in format YYYY-MM-DD (e.g., {date.today().strftime('%Y-%m-%d')}): ")
# 将字符串转换成日期对象
try:
birth_date = date.fromisoformat(birth_date_str)
except ValueError:
print("Invalid date format, please try again.")
else:
# 获取今天的日期
today = date.today()
if is_birthday(today, birth_date):
print(f"\n{name}, it's your birthday today! Here's a random wish for you:")
print(random.choice(bday_wishes))
else:
days_left = (birth_date - today).days
if days_left <= 0:
print("It's almost your birthday! Get ready for some celebration!")
elif days_left < 7:
print(f"Just {abs(days_left)} more days until your big day, {name}!")
else:
print(f"{abs(days_left)} days to go until {name}'s birthday.")
# 如果不是生日,但接近,也提供一些温馨的提醒
```
这段代码会让用户输入名字和生日,然后检查今天是否是他们的生日,如果不是,则显示距离生日还有多少天。如果是,就会从祝福语列表中随机选一条发送给他们。
阅读全文