【问题标题】:Call Cost Calculator Python Exercise通话费用计算器 Python 练习
【发布时间】:2021-02-16 03:07:24
【问题描述】:

我正在为初学者学习 Python 课程。但是,我正在努力解决以下问题:

运动描述

编写一个计算长途电话费用的程序。通话费用为 根据以下费率表确定:

• 上午 8:00 之间开始的任何通话。周一至周五下午 6:00 是 按每分钟 0.40 美元的费率计费。

• 上午 8:00 之前开始的任何通话。或周一至周五下午 6:00 之后,是 按每分钟 0.25 美元的费率收费。

• 周六或周日拨打的任何电话均按每人 0.15 美元的费率收费 分钟。

输入将包括星期几、通话开始时间和通话时长 在几分钟内通话。 输出将是调用的成本。

注意事项:

  1. 时间输入为4位数字,代表24小时制时间 符号,所以时间是下午 1:30输入为 1330

  2. 星期几将被读取为以下三个字符串之一: “周一”、“周二”、“周三”、“周四”、“周五”、“周六”或“周日”

  3. 分钟数将作为正整数输入。

例如,执行可能如下所示:

输入通话开始的日期:星期五

输入通话开始的时间(hhmm):2350

输入通话时长(以分钟为单位):22

此通话费用为 5.50 美元

我编写的代码:

week = str(input("Enter the day call started at: "))
hour_started = int(input("Enter the time the call started at (hhmm): "))
duration = int(input("Enter the duration of the call (in minutes): "))

if(week == "Mon") or (week == "Tue") or (week == "Wed") or (week == "Thr") or (week == "Fri"):
    if(int(hour_started > 1800) and int(hour_started <= 2400)) or (int(hour_started < 800) and int(hour_started >= 0)):
     tarif2 = float(duration * 0.25)
     print("This call will cost " + '$' + '%.2f' % float(tarif2), sep="")
    if(int(hour_started >= 800) and int(hour_started <= 1800)):
     tarif3 = float(duration * 0.40)
     print("This call will cost " + '$' + '%.2f' % float(tarif3), sep="")
else:
    tarif1 = float(duration * 0.15)
    print("This call will cost " + '$' + '%.2f' % float(tarif1), sep="")

我知道我的代码没有导入时间模块,但是任务似乎不需要这样。关联的自动评分器正在返回一个错误,该错误似乎与数学无关,而是与 I/O 相关:

Test Failed: 'enter the day call started at:  this call will cost $5.50' != 'this call will cost $5.50'

非常感谢您提前提供的帮助!

【问题讨论】:

  • 根据错误,您在input() 中输入的字符串似乎引起了问题。
  • 我认为可能是这种情况,但对input() 的更改似乎都没有效果。
  • 可以分享这个练习吗,也许我可以帮忙,因为没有你已经指出的任何数学错误。
  • 感谢您的帮助!我的帖子中描述的练习就是我所拥有的。然后我将我的代码上传到一个自动评分器,它返回“测试失败......”行。你有什么想法,我怎么能改变input()
  • 可能跟Array的有关系?

标签: python-3.x


【解决方案1】:

既然问题已经解决,我想指出一些改进,您可以开始对代码进行改进,使其看起来更干净,就像众所周知的 Python 一样。

week = input("Enter the day call started at: ").lower()
hour_started = int(input("Enter the time the call started at (hhmm): "))
duration = int(input("Enter the duration of the call (in minutes): "))

if week in ['mon', 'tue', 'wed', 'thr', 'fri']:
    if (hour_started > 1800 and hour_started <= 2400) or (hour_started < 800 and hour_started >= 0):
        cost = duration * 0.25
        print(f"This call will cost ${cost}")
    elif hour_started >= 800 and hour_started <= 1800:
        cost = duration * 0.40
        print("This call will cost ${}".format(cost))
else:
    cost = duration * 0.15
    print("This call will cost " + '$' + '%.2f' % float(cost), sep="")

上面的代码也可以正常工作。我最初写这篇文章是为了解决这个练习,所以想分享一下。

快乐学习:)

【讨论】:

  • 非常感谢!我想知道如何进一步简化代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多