How is the print function used in Python?
The print function is used to display output, which can include strings, variables, expressions, and more.
Basic usage:
print('Hello, World!') # 打印字符串
print(123) # 打印整数
print(3.14) # 打印浮点数
When printing multiple items, you can separate them with commas.
name = 'Alice'
age = 20
print('My name is', name, 'and I am', age, 'years old.') # 打印多个字符串和变量
Strings can be concatenated using the plus sign.
name = 'Alice'
age = 20
print('My name is ' + name + ' and I am ' + str(age) + ' years old.') # 字符串拼接和类型转换
You can format output using placeholders.
name = 'Alice'
age = 20
weight = 60.5
print('My name is %s and I am %d years old. My weight is %.1f kg.' % (name, age, weight)) # 使用占位符格式化输出
In Python 3.6 and later versions, you can also use f-strings for formatting output.
name = 'Alice'
age = 20
weight = 60.5
print(f'My name is {name} and I am {age} years old. My weight is {weight:.1f} kg.') # 使用f-string格式化输出
Important notes:
- By default, the print function will add a newline character at the end of the output. If you do not want a newline, you can use the end parameter to control it, for example: print(‘Hello’, end=”).
- The print function can take multiple arguments and automatically add spaces to separate them, for example: print(‘Hello’, ‘World’) will output Hello World.
- The parameters of the print function can be objects of any type. If you need to output a custom object, you can specify the object’s string representation by defining the __str__ method in the class.