在Python中,`print`函数用于在控制台上输出文本或变量的值。以下是`print`函数的基本用法:
print("Hello, World!") 输出字符串 "Hello, World!"
print(123) 输出整数 123
print(3.14) 输出浮点数 3.14
print("My name is", "Alice", "and I am", 20, "years old.") 输出多个字符串和变量
`print`函数可以接受多个参数,并使用逗号分隔。如果要在输出中包含变量的值,可以使用字符串格式化:
x = 10
print("The value of x is", x) 输出 "The value of x is 10"
`print`函数还支持以下参数:
`end`:指定打印结束时的字符串,默认为换行符 `\n`。
`file`:指定输出的文件对象,默认为 `sys.stdout`,即屏幕输出。
`flush`:指定是否立即刷新输出,默认为 `False`,即不立即刷新。
例如,使用逗号和空格作为分隔符,不换行输出:
print(1, 2, 3, sep=", ", end="") 输出 "1, 2, 3"
还可以使用 f-string 进行格式化输出,这在Python 3.6及以上版本中可用:
name = "Alice"
age = 20
print(f"My name is {name} and I am {age} years old.") 输出 "My name is Alice and I am 20 years old."