首页 > 解决方案 > 为什么我的警报代码没有在最后打印消息?

问题描述

所以我对 Python 还很陌生,我正在尝试为计时器编写代码。我的代码应该得到小时、分钟,无论是上午还是下午,以及他们希望程序在计时器完成后打印出来的消息。到目前为止,程序会询问几个问题并将它们存储在变量中,但完成后不会打印出消息。

我试过查看代码的每一部分,代码相当简单,所以我不明白为什么会这样。

# Set up variables
hour = int(input('What should the hour be? '))

minute = input('What should the minute be? ')

ampm = input('A.M. or P.M.? ')

if (ampm == 'A.M.'):
     if (hour == 12):
    hour = 0
    else:
         hour = hour

 if (ampm == 'P.M.'):
     if (hour == 12):
         hour = hour 
     else:
         hour = hour + 12

message = input('What should the message be? ')

import datetime

current_hour = datetime.datetime.today().strftime('%H')

current_minute = datetime.datetime.today().strftime('%M')

alarm = True

# Set up loop
while (alarm):
    if (hour != datetime.datetime.today().strftime('%H')):
      alarm = True
    else:
        if (minute == datetime.datetime.today().strftime('%M')):
          print(message)
          alarm = False
        else: 
            alarm = True

它应该打印出用户输入的消息。它不是那样做的。

标签: python

解决方案


的变量hour返回一个 int 值并datetime.datetime.today().strftime('%H')返回字符串,因此您的程序进入无限循环。更改条件如

        if (hour != int((datetime.datetime.today().strftime('%H')))):

推荐阅读