【问题标题】:How can I display a colon in an output for displaying times?如何在输出中显示冒号以显示时间?
【发布时间】:2017-04-15 16:03:13
【问题描述】:

输出应以以下格式显示时间:上午 8:00

def save_time():
     cse_info = {}
     again = 'Y'     
     while again.lower() == 'y':

             cse_num = int(input('Enter course number:'))
             cse_time = int(input('Enter course meeting time:'))

             cse_info['CS' + str(cse_num)] = str(cse_time) + ' a.m.'         
             again = input('Do you want to enter another course?')        
     print(cse_info)

save_time()

【问题讨论】:

  • 您希望cse_time 提供什么输入?像“0833”这样的东西?
  • 尝试创建一个接受数字并显示此格式的输入:8:00
  • 先修正缩进,缩进不好的问题无法回答
  • 所有数字都应该产生8:00吗?如果我输入850怎么办?
  • @vishes_shell 你怎么确定这是while循环下的正确缩进? OP是不是这么说的?如果您不确定 100%,请不要编辑问题。接下来的三行也可能在 while 循环下。等待操作

标签: python string integer output


【解决方案1】:

看起来你需要一种方法来退出你的 while 循环......否则它应该可以工作。

def save_time():

         cse_info = {}
         again = 'Y'

         while again.lower() == 'y':

             cse_num = int(input('Enter course number:'))
             cse_time = int(input('Enter course meeting time:'))
             break # maybe you want to check for an exit condition?

         cse_info['CS' + str(cse_num)] = str(cse_time) + ' a.m.'

         again = input('Do you want to enter another course?')

         print(cse_info)


save_time()

这次我会为你做的,但这不是一个家庭作业网站。

def save_time():
         cse_info = {}
         while True:
             cse_num = int(input('Enter course number:'))
             cse_time = int(input('Enter course meeting time:'))
             cse_info['CS' + str(cse_num)] = str(cse_time) + ' a.m.'
             again = input('Do you want to enter another course? (1=yes 2=no')
             if not again: break

         print(cse_info)

save_time()

【讨论】:

  • 看起来缩进很差,OP可能在while循环下缩进了所有内容,因此由于again变量的变化,可以退出while循环。这不是问题
【解决方案2】:

如果cse_time 的输入格式为“0800”为“8:00”,则可以将str(cse_time) + ' a.m.' 替换为str(cse_time)[:2]+":"+str(cse_time)[2:] + ' a.m.' 以添加分号。或者你可以让cse_time 是一个字符串,所以输入可以是8:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多