Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeError:必须是str,而不是int--Python错误_Python - Fatal编程技术网

TypeError:必须是str,而不是int--Python错误

TypeError:必须是str,而不是int--Python错误,python,Python,如果我尝试运行函数absolutevalue(4),它会抛出如下错误 def absolutevalue(num): if num >= 0: abs_num = num else: abs_num = -num print("The absolute value"+ abs_num) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 绝对值(4) 文件“”,第6行,绝对值 打印(“绝对值

如果我尝试运行函数
absolutevalue(4)
,它会抛出如下错误

def absolutevalue(num):
        if num >= 0:
            abs_num = num
        else:
            abs_num = -num
        print("The absolute value"+ abs_num)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
绝对值(4)
文件“”,第6行,绝对值
打印(“绝对值”+abs_num)
TypeError:必须是str,而不是int

您需要更改此行

Traceback (most recent call last):

  File "<ipython-input-16-36bd355eb83d>", line 1, in <module>
    absolutevalue(4)

  File "<ipython-input-15-42a3de37c325>", line 6, in absolutevalue
    print("The absolute value"+ abs_num)

TypeError: must be str, not int
将来

Python在这一行给了您一个错误,因为您只能使用
+
运算符来连接两个字符串或将两个整数相加不能将整数添加到字符串或将字符串与整数连接起来。这是Python中糟糕的语法

您可以使用整数的字符串版本来修复此问题

print("The absolute value"+ abs_num)

高效快捷的方法是:

print("The absolute value"+ str(abs_num))
在Python的最新版本3.7中,我们现在已经格式化了字符串:

print("The absolute value {}".format(abs_num))
print("The absolute value"+ str(abs_num))
print("The absolute value {}".format(abs_num))
print(f'The absolute value {abs_num}')