该错误显示:“TypeError:第 39 行上的 Add 的操作数类型不受支持:'int' 和 'str'”。这是什么意思以及如何解决这个问题?这是代码:
import time
TimeIsUp=0
print ("Timer")
h=int(input("Hours-"))
m=int(input("Minutes-"))
if m>59:
while m>0 and m!=0:
m-=60
h+=1
m+=60
h-=1
s=int(input("Seconds-"))
if s>59:
while s>0 and s!=0:
s-=60
m+=1
s+=60
m-=1
while m>=0 and m!=0:
m-=60
h+=1
m+=60
h-=1
while TimeIsUp==0:
s-=1
if s<0 and m>0:
s+=61
m-=1
if m<0 and h>0:
m+=61
h-=1
else:
if h>0:
s+=61
m+=59
h-=1
else:
TimeIsUp==1
print (h+":"+m+":"+s)
time.sleep(1)
print ("Time's Up!")
Run Code Online (Sandbox Code Playgroud)
“时间”从https://trinket.io/python导入(因为这是我作为初学者编写 Phython 时使用的)。
TypeError:第 39 行上的 Add 不支持的操作数类型:'int' 和 'str'”。这是什么意思
这意味着在代码的第 #39 行,您尝试添加(“+”运算符)一个整数和一个字符串 - 这是没有意义的。阅读你的代码,这显然是这一行:
print h+":"+m+":"+s
Run Code Online (Sandbox Code Playgroud)
请注意,字符串将“+”运算符实现为字符串连接,而整数将其实现为(当然)加法。
我该如何解决这个问题?”
您可以将整数转换为字符串,如其他评论或答案中提到的那样,但这里正确的解决方案是使用字符串格式化操作:
print "{}:{}:{}".format(h, m, s)
Run Code Online (Sandbox Code Playgroud)
或者如果你想更明确
print "{hour}:{minutes}:{seconds}".format(hour=h, minutes=m, seconds=s)
Run Code Online (Sandbox Code Playgroud)
str.format()将处理必要的转换等,并且还提供更高级的格式化操作(数字前导零等)。