如何在print语句中插入字符串和变量?嵌套print输出None问题解决
错误原因
你输出None的根源是Python中print()函数没有返回值,无显式return的函数默认返回None。你在外层print中嵌套调用print(yPos)、print(xPos)时,这两个嵌套的print会先执行、单独打印变量值,之后它们返回的None会被作为参数传入外层print,最终就出现了夹杂None的异常输出。
修复方案
不需要在print里嵌套调用print,Python支持多种直接拼接字符串和变量的写法,选任意一种都可以:
- 逗号分隔传参(和你原有写法逻辑最接近)
print支持传入多个不同类型的参数,默认用空格拼接后输出,直接把变量作为参数传入即可:sidewalkclosed = True raining = True xPos = 400 yPos = 400 print("Your robot is located at", yPos, "on the y axis and", xPos, "on the x axis.") - f-string格式化(Python3.6及以上版本推荐,可读性最好)
在字符串前加f标记,字符串内部用{变量名}直接嵌入需要输出的变量:sidewalkclosed = True raining = True xPos = 400 yPos = 400 print(f"Your robot is located at {yPos} on the y axis and {xPos} on the x axis.") - str.format()格式化(兼容所有Python3版本)
在字符串中用{}作为占位符,调用字符串的format方法按顺序传入变量:sidewalkclosed = True raining = True xPos = 400 yPos = 400 print("Your robot is located at {} on the y axis and {} on the x axis.".format(yPos, xPos))
注:你定义的
sidewalkclosed、raining两个变量没有在这段输出逻辑中使用,不影响当前打印结果,如果后续逻辑不需要可以删除。
内容的提问来源于stack exchange,提问作者Killjoy
相关产品推荐
相关产品推荐

