python的print函数解释与使用示例
时间: 2024-02-23 13:38:24 浏览: 20
print函数是Python内置的输出函数,用于将结果输出到控制台或文件中。它可以接受任意数量的参数,并将它们打印出来,以空格分隔,并在末尾添加一个换行符。
以下是print函数的使用示例:
1.输出字符串
print("Hello World")
2.输出变量
name = "Alice"
print("My name is", name)
3.输出表达式
a = 10
b = 20
print("The sum of", a, "and", b, "is", a + b)
4.格式化输出
age = 25
print("I am %d years old." % age)
5.格式化输出-使用f-string
name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
6.输出到文件
with open("output.txt", "w") as f:
print("Hello World", file=f)
以上是print函数的使用示例,可以根据需要进行调整和扩展。