How is the print function used in Python?
In Python, you can use the print function to display text or the value of variables. The basic syntax for the print function is:
print(value1, value2, value3, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Among them:
- value1, value2, value3, etc. are the values or variables to be printed, which can be multiple and separated by commas.
- “sep is used to separate different values within a string, defaulting to a single space.”
- end is used to specify the string to print at the end, with the default being the newline character ‘\n’.
- The “file” parameter is used to specify the output file object, with the default being sys.stdout which represents screen output.
- The flush parameter is a boolean value that determines whether to immediately refresh the output, with the default being False, meaning it does not refresh immediately.
Here are some examples:
print("Hello, World!") # 打印文本
print(3 + 4) # 打印表达式的结果
x = 10
print("The value of x is", x) # 打印文本和变量
print(1, 2, 3, sep=', ') # 使用逗号和空格作为分隔符
print("Hello", end=' ')
print("World!") # 不换行输出
The output results of the above code are:
Hello, World!
7
The value of x is 10
1, 2, 3
Hello World!