如何打印给定输入的上一个和下一个数字?

2024-03-28 14:03:15 发布

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

def printPreviousAndNext():
  take = input()
  print("The next number for the number" + take + "is" + int(take+1))
  print("The previous number for the number" + take + "is" + int(take-1))
printPreviousAndNext()

如您所见,我想输入并打印其上一个和下一个数字,例如:

my input: 200

我希望结果是:

The next number for the number 200 is 201
The previous number for the number 200 is 199

但我得到一个错误如下:

Traceback (most recent call last):
  File "python", line 5, in <module>
  File "python", line 3, in printPreviousAndNext
TypeError: can only concatenate str (not "int") to str

我的错在哪里


Tags: theinnumberforinputislinefile
1条回答
网友
1楼 · 发布于 2024-03-28 14:03:15

错误消息实际上说明了一切,您正在尝试连接一个字符串和一个数字,您真正想要的是连接两个字符串

def printPreviousAndNext():
  take = int(input())
  print(f"The next number for the number {take} is {take+1}")
  print(f"The previous number for the number {take} is {take-1}")
printPreviousAndNext()

用f-string格式化甚至可以处理转换。(@Matthias)

相关问题 更多 >