【问题标题】:Python function that takes two values [duplicate]接受两个值的Python函数[重复]
【发布时间】:2016-10-26 12:21:06
【问题描述】:

这个函数有两个整数,x 是小时,y 是分钟。该函数应将文本中的时间打印到最接近的小时。 这是我写的代码。

def approxTime(x, y):
    if int(y) <= 24:
        print("the time is about quarter past" + int(y))
    elif 25 >= int(y) <=40:
        print("the time is about half past" + int(y))
    elif 41 >= int(y) <= 54:
        print("the time is about quarter past" + int(y+1))
    else:
        print("the time is about" + int(y+1) +"o'clock")
approxTime(3, 18)

但是我收到此错误消息。

  Traceback (most recent call last):   File
  "C:/Users/Jafar/Documents/approxTime.py", line 14, in <module>
      approxTime(3, 18)   File "C:/Users/Jafar/Documents/approxTime.py", line 5, in approxTime
      print("the time is about quarter past" + int(y)) TypeError: Can't convert 'int' object to str implicitly

【问题讨论】:

  • 不要打电话给int(y+1) 打电话给str(int(y)+1) 或者最好再用str.format
  • 顺便说一句,它应该是x,而不是print 语句中的y - 请将变量名称更改为hoursminutes 或类似的东西,以使事情多一点很明显。
  • 下次尝试谷歌搜索错误信息。
  • 错误信息对我来说似乎很清楚。为什么会出现混乱?您正在尝试使用 + 运算符连接 strint。它告诉你你不能那样做。您需要将int 转换为str。当你应该做"x" + "5"时,你正在尝试做"x" + 5。错误信息基本上告诉了你这一点。只需阅读错误消息,查看代码,思考并相应地修改您的代码。
  • 请不要在得到答案后破坏您的问题。

标签: python function python-3.x if-statement


【解决方案1】:

您正在尝试连接字符串和整数对象!将对象y(或y+1)转换为字符串,然后追加。喜欢:

print("the time is about quarter past" + str(y)) #similarly str(int(y)+1)

【讨论】:

  • y 是一个字符串,我认为添加 1 你需要str(int(y) + 1)
  • 正确,我刚刚在答案中解决了这个问题。
  • @SuperSaiyan if y 是一个字符串我猜它应该是 str(int(y)+1) 大于 str(int(y+1))
  • @mgc:这是一个错字,已修复。感谢您的指出。
【解决方案2】:

你必须转换成一个字符串。您正在尝试将不兼容的 int 和字符串连接在一起。

def approxTime(x, y):
     if int(y) <= 24:
         print("the time is about quarter past" + str(y))
     elif 25 >= int(y) <=40:
         print("the time is about half past" + str(y))
     elif 41 >= int(y) <= 54:
         print("the time is about quarter past" + str(y+1))
     else:
         print("the time is about" + str(y+1) +"o'clock")
approxTime(3, 18)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2018-04-20
    • 2014-12-27
    • 2015-07-24
    • 2014-12-13
    • 2021-05-30
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多