接受两个值的Python函数

2024-05-29 02:06:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这个函数取两个整数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

Tags: the函数timeisusersfileintabout
2条回答

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

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

你得把它放在弦上。您正在尝试将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)

相关问题 更多 >

    热门问题