接受两个值的Python函数

接受两个值的Python函数,python,function,python-3.x,if-statement,Python,Function,Python 3.x,If Statement,这个函数取两个整数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

这个函数取两个整数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)
def近似时间(x,y):

如果int(y)=int(y)=int(y)您正在尝试连接字符串和整数对象!将对象
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)
def近似时间(x,y):

如果int(y)=int(y)=int(y)不调用
int(y+1)
调用
str(int(y)+1)
或者最好再次使用
str.format
顺便说一句,它应该是
x
,在
print
语句中不
y
-请将变量名称更改为
hours
minutes
或类似的名称,使事情变得更明显。下次,尝试用谷歌搜索错误消息。错误消息对我来说似乎非常清楚。为什么会出现混乱?您正试图用
+
运算符连接
str
int
。它告诉你你不能那样做。您需要将
int
转换为
str
。当您应该执行
“x”+“5”
时,您正在尝试执行
“x”+“5”
。错误消息基本上告诉了您这一点。只需阅读错误消息,查看代码,思考它,并相应地修改代码。在得到答案后,请不要破坏您的问题。
y
是一个字符串,我认为可以添加1。您需要
str(int(y)+1)
更正,我刚刚在回答中修正了这个问题。@SuperSaiyan如果
y
是一个字符串,我想应该是str(int(y)+1)而不是str(int(y+1))@mgc:这是一个打字错误,修正了这个问题。谢谢你的指点。
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)