You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数赋值变量后导入出现None值问题求助

问题根源与解决方法

你的问题出在函数的输出方式上——你用了print()来输出拼接后的字符串,但print()函数本身不会返回任何有效值(它默认返回None)。

当你执行city_country_var = city_country('Punto Fijo', 'Venezuela')时,函数内部会先执行print()把拼接好的字符串打印出来,然后因为函数没有指定return语句,Python会自动让它返回None,所以city_country_var的值就是None。当你后续打印这个变量时,就会出现Punto Fijo, Venezuela None(前半段是函数内部print的结果,后半段是变量的None)。

解决步骤

只需要把函数里的print()改成return,让函数返回拼接后的字符串即可,这样既符合单元测试的需求(单元测试一般断言函数的返回值),也能让变量正确获取到结果:

def city_country(city_name, country_name):
    """Simple function that returns City, Country formatted string"""
    return f"{city_name.title()}, {country_name.title()}"

测试验证

现在再执行赋值操作:

city_country_var = city_country('Punto Fijo', 'Venezuela')
print(city_country_var)

输出就会是:

Punto Fijo, Venezuela

对于unittest单元测试,你可以这样写测试用例(断言返回值是否符合预期):

import unittest

class TestCityCountry(unittest.TestCase):
    def test_city_country_format(self):
        result = city_country('Punto Fijo', 'Venezuela')
        self.assertEqual(result, 'Punto Fijo, Venezuela')

if __name__ == '__main__':
    unittest.main()

这样就能顺利通过单元测试啦!

内容的提问来源于stack exchange,提问作者Akaidmaru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:23:22