在Python中,`print()`函数用于在控制台打印输出。以下是一些基本的使用方法:
1. 打印字符串:
print("Hello, World!")
2. 打印变量的值:
x = 10
print(x)
3. 打印多个变量的值:
x = 10
y = 5
print(x, y)
4. 打印表达式的结果:
x = 10
y = 5
print(x + y)
5. 格式化输出:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
或者使用f-string:
name = "Bob"
age = 25
print(f"My name is {name} and I am {age} years old."
6. 打印列表:
list_example = ['apple', 'banana', 'orange']
print(list_example)
7. 打印元组:
tuple_example = (1, 2, 3, 4)
print(tuple_example)
8. 打印字典:
dict_example = {'name': 'Alice', 'age': 30}
print(dict_example)
9. 自定义对象的打印:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Bob", 25)
print(person)
10. 控制输出的分隔符和结尾字符:
print("Hello", "World!", sep=", ", end="!\n")
以上是Python中打印的基本方法。您可以根据需要选择不同的打印方式