在Python中,print()函数主要用于在控制台上输出文本。它可以接受多种类型的参数,如字符串、整数、浮点数等,并将它们转换为字符串以便在屏幕上显示。以下是一些常见的使用方法:
print("Hello, World!")输出变量:name = "Alice"age = 30print("My name is", name, "and I am", age, "years old.")使用格式化字符串(f-string):name = "Bob"age = 25print(f"My name is {name} and I am {age} years old.")输出列表、元组或字典:my_list = [1, 2, 3]my_tuple = (4, 5, 6)my_dict = {"key1": "value1", "key2": "value2"}print("List:", my_list)print("Tuple:", my_tuple)print("Dictionary:", my_dict)设置分隔符和结束符:print("apple", "banana", "cherry", sep="-", end="!\n")这将输出:apple-banana-cherry!
with open("output.txt", "w") as file: print("Hello, World!", file=file)这将把"Hello, World!"写入名为"output.txt"的文件中。
这只是print()函数的一些基本功能。通过组合不同的参数和格式化选项,你可以根据需要定制输出内容。




