pyhello 发表于 2023-6-11 17:39:27

请问大神

def fun1():
    return 'hello'
def fun2():
    return 'world'
请问大神怎么能显示 hello world呢 print(fun1()+fun2())的写法好像不对

isdkz 发表于 2023-6-11 17:40:47

如果你想在 fun1 和 fun2 返回的字符串之间添加空格来得到"hello world",你需要在两个函数调用之间添加一个包含空格的字符串。这是如何做的:

print(fun1() + ' ' + fun2())


这样会首先打印出 fun1 的返回结果(也就是"hello"),然后打印一个空格,最后打印出 fun2 的返回结果(也就是"world")。这样结果就是你期望的"hello world"了。

liuhongrun2022 发表于 2023-6-11 17:42:16

这样:
print(fun1(), fun2())

sfqxx 发表于 2023-6-11 17:43:19

您可以使用字符串的连接运算符 "+" 来将两个函数的返回值连接起来。例如:

print(fun1() + ' ' + fun2())

在这个表达式中,`fun1()` 返回 `"hello"`,而 `fun2()` 返回 `"world"`。在两个函数调用之间添加一个空格使输出的结果变成 `"hello world"`。

请注意,原始代码中的问题是使用 Python 的字符串连接运算符 `+` 来连接两个函数调用,这是错误的,因为这两个函数调用返回的是字符串类型而不是数字类型。因此需要在两个字符串之间添加一个空格才能使其以正确的格式输出。

给个最佳答案{:10_254:}

pyhello 发表于 2023-6-11 17:51:37

isdkz 发表于 2023-6-11 17:40
如果你想在 fun1 和 fun2 返回的字符串之间添加空格来得到"hello world",你需要在两个函数调用之间添加一 ...

报错提示是 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' ,大神麻烦再看下

pyhello 发表于 2023-6-11 17:52:23

sfqxx 发表于 2023-6-11 17:43
您可以使用字符串的连接运算符 "+" 来将两个函数的返回值连接起来。例如:




报错提示是 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' ,大神麻烦再看下

isdkz 发表于 2023-6-11 17:52:55

pyhello 发表于 2023-6-11 17:51
报错提示是 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' ,大神麻烦再看下

你是不是没有用 return,完整的代码是这样的:

def fun1():
    return 'hello'


def fun2():
    return 'world'

print(fun1() + ' ' + fun2())

pyhello 发表于 2023-6-11 17:53:57

本帖最后由 pyhello 于 2023-6-11 17:56 编辑

感谢大神!!!

sfqxx 发表于 2023-6-11 17:55:26

pyhello 发表于 2023-6-11 17:52
报错提示是 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' ,大神麻烦再看下

这个错误提示表明在执行 `fun1()` 或者 `fun2()` 函数时,其中一个函数返回了 None,而将它们的返回值进行字符串拼接的操作是不支持将 None 和字符串拼接的。因此需要检查 `fun1()` 和 `fun2()` 的实现并确保它们都返回非空字符串,例如:


def fun1():
    return "Hello"

def fun2():
    return "world"

print(fun1() + ' ' + fun2())



输出结果应为:“Hello world”

求最佳答案{:10_254:}

歌者文明清理员 发表于 2023-6-11 20:03:11

sfqxx 发表于 2023-6-11 17:55
这个错误提示表明在执行 `fun1()` 或者 `fun2()` 函数时,其中一个函数返回了 None,而将它们的返回值进 ...

……

sfqxx 发表于 2023-6-11 20:26:50

歌者文明清理员 发表于 2023-6-11 20:03
……

{:5_95:}
页: [1]
查看完整版本: 请问大神