将整数“隐式”更改为字符串??Python

2024-10-17 08:30:53 发布

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

我想知道是否有人能帮我。我真的是新手,我需要把我的输入转换成一个字符串?你知道吗

# Python program to calculate the Fibonacci numbers
def fibR(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fibR(n - 1) + fibR(n - 2)

# Request input from the user
num = int(input("Please enter the number in the Fibonacci sequence you wish to calculate: "))

#
if num == 1:
    print("The Fibonacci number you have requested is" + 1 + ".")
else :
    print("The Fibonacci number you have requested is" + fibR(num) + ".")

Tags: thetoyounumberinputreturnifhave
3条回答

执行^{}将数字转换为字符串。你知道吗

您已经正确地将input转换为int。但是,在print语句中。。。你知道吗

print("The Fibonacci number you have requested is" + fibR(num) + ".")

……函数fibR(num)返回一个整数。当您尝试将返回的整数与字符串连接起来时,会导致错误。您需要做的是使用格式字符串:

print("The Fibonacci number you have requested is {}.".format(fibR(num))) 

else语句中使用%

print("The Fibonacci number you have requested is %d." % fibR(num))

相关问题 更多 >