优秀的编程知识分享平台

网站首页 > 技术文章 正文

在 Python 中创建一个简单的闹钟

nanyue 2025-02-13 13:32:02 技术文章 8 ℃

在本教程中,我们制作一个简单的闹钟,来提升你的Python技能。

在闹钟程序中,用户需要设置闹铃时间,时间到,发出提示音及提示信息。

输入设置闹钟时间

1.导入日期和时间模块。

import datetime

import time

2.添加 while 循环。

在 while 循环中,要求用户输入有效的闹钟时间,格式为 [小时:分钟]。

invalid = True
while(invalid):
    userInput = input("设置闹钟时间(例:08:10):")

3.将用户的输入的时间将小时与分钟分开处理。

?? alarmTime = [int(n) for n in userInput.split(":")]

4.验证小时和分钟是否有效。

小时应为 0 到 23 之间的数字,分钟应为 0 到 59 之间的数字。如果不满足这些条件, while 循环重复并要求用户输入新值。

    if alarmTime[0] >= 24 or alarmTime[0] < 0:
        invalid = True
    elif alarmTime[1] >= 60 or alarmTime[1] < 0:
        invalid = True
    else:
        invalid = False

计算闹钟等待时间

1.将闹钟时间转换为秒数。

seconds_hms = [3600, 60, 1]
alarmSeconds = sum([a*b for a,b in zip(seconds_hms[:len(alarmTime)], alarmTime)])

2.使用 datetime.now() 函数确定当前时间。

now = datetime.datetime.now()
currentTimeInSeconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])

3.计算闹钟响起前必须等待的秒数。

secondsUntilAlarm = alarmSeconds - currentTimeInSeconds

如果时间差为负数,则意味着闹钟设置在第二天。

if secondsUntilAlarm < 0:
    secondsUntilAlarm += 86400

向用户发送一条消息,提示闹钟已成功设置。

print("闹钟设置完毕!")
print("闹钟将在 %s 后响起!" % datetime.timedelta(seconds=secondsUntilAlarm))

敲响闹钟

在闹钟响起之前添加倒计时。

若要为每秒添加倒计时,请使用 for 循环打印留给用户的秒数。

添加一个 for 循环,直到警报响起,并向用户显示剩余的秒数。

for i in range(0, secondsUntilAlarm):
    time.sleep(1)
    secondsUntilAlarm -= 1
    print(datetime.timedelta(seconds=secondsUntilAlarm))

当闹钟响起时,向用户发送信息。

print("铃铃铃……!时间到了!")

导入模块,import winsound

系统发出提示音。

duration = 3000 
freq = 440  
winsound.Beep(freq, duration)

「完整代码:」

import datetime
import time
import winsound
invalid = True
while(invalid):
    userInput = input("设置闹钟时间(例:08:10): ")
    alarmTime = [int(n) for n in userInput.split(":")]
    if alarmTime[0] >= 24 or alarmTime[0] < 0:
        invalid = True
    elif alarmTime[1] >= 60 or alarmTime[1] < 0:
        invalid = True
    else:
        invalid = False    
    seconds_hms = [3600, 60, 1]
    alarmSeconds = sum([a*b for a,b in zip(seconds_hms[:len(alarmTime)], alarmTime)])
    now = datetime.datetime.now()
    currentTimeInSeconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
    secondsUntilAlarm = alarmSeconds - currentTimeInSeconds
    if secondsUntilAlarm < 0:
        secondsUntilAlarm += 86400
    print("闹钟设置完毕!")
    print("闹钟将在 %s 后响起!" % datetime.timedelta(seconds=secondsUntilAlarm))
    for i in range(0, secondsUntilAlarm):
        time.sleep(1)
        secondsUntilAlarm -= 1
        print("\r",datetime.timedelta(seconds=secondsUntilAlarm),end="",flush=True)
    print("\n铃铃铃……!时间到了!")
    duration = 3000
    freq = 440
    winsound.Beep(freq, duration)

?

文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!

?

最近发表
标签列表