在Python 3及更高版本中,print是函数而不是关键字。
print('hello world!')
# 出:你好世界!
foo = 1
bar = 'bar'
baz = 3.14
print(foo)
# 出:1
print(bar)
# 出:酒吧
print(baz)
# 出:3.14您还可以将许多参数传递给print:
print(foo, bar, baz) # 出:1 bar 3.14
print多个参数的另一种方法是使用+
print(str(foo) + " " + bar + " " + str(baz)) # 出:1 bar 3.14
+但是,在用于打印多个参数时,应注意的是,参数的类型应该相同。尝试打印上面的示例而没有强制转换为stringfirst会导致错误,因为它将尝试将数字添加1到字符串"bar"并将其添加到number 3.14。
# 错误: # 类型:int str float print(foo + bar + baz) # 会导致错误
这是因为print将首先评估的内容:
print(4 + 5)
# 出:9
print("4" + "5")
# 出:45
print([4] + [5])
# 出:[4,5]否则,使用a+对用户读取变量的输出会非常有帮助。在下面的示例中,输出非常易于阅读!
下面的脚本演示了这一点
import random
#告诉python包含创建随机数的函数
randnum = random.randint(0, 12)
#设定介于0到12之间的随机数,并将其分配给变量
print("The randomly generated number was - " + str(randnum))您可以print使用以下end参数阻止该功能自动打印换行符:
print("t他的结尾没有换行符... ", end="")
print("see?")
# out: t他的结尾没有换行符... see?如果要写入文件,可以将其作为参数传递file:
with open('my_file.txt', 'w+') as my_file:
print("t他去了文件!", file=my_file)这转到文件!