无法将int隐式更改为str

2024-09-27 21:26:26 发布

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

我试图创建一个程序,要求用户输入上次看到哈雷彗星的年份,然后再加上75年和76年,然后输出结果。你知道吗

lastsight = int(input("When was the last sighting? "))
firstsight = lastsight + 75 
secondsight = lastsight + 76
print("The next sighting will be in", firstsight,  "or", secondsight + ".")

但是,无论何时运行它,都会出现以下错误:

Traceback (most recent call last):
File "program.py", line 5, in <module>
print("The next sighting will be in", firstsight,  "or", secondsight + ".")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

如果能帮我修一下,我将不胜感激。你知道吗


Tags: orthe用户in程序bewillnext
2条回答

使用以下选项:

print("The next sighting will be in", firstsight,  "or", str(secondsight) + ".")

正如您正确观察到的,python不会隐式地执行这些转换。你知道吗

试试这个:

print("The next sighting will be in {} or {}.".format(firstsight,  secondsight))

相关问题 更多 >

    热门问题