python print打印变量所有用法
时间: 2023-11-22 19:05:06 浏览: 122
在 Python 中,使用 `print()` 函数可以将字符串或变量的值输出到控制台。下面是 `print()` 函数打印变量的几种用法:
1. 输出变量的值:
```python
x = 10
print(x) # 输出:10
```
2. 使用格式化字符串输出变量的值:
```python
x = 10
print(f"The value of x is {x}") # 输出:The value of x is 10
```
3. 将多个变量的值一起输出:
```python
x = 10
y = 20
print(x, y) # 输出:10 20
```
4. 将多个变量的值格式化后一起输出:
```python
x = 10
y = 20
print(f"The value of x is {x}, and the value of y is {y}") # 输出:The value of x is 10, and the value of y is 20
```
5. 使用不同的分隔符将多个变量的值输出:
```python
x = 10
y = 20
print(x, y, sep="---") # 输出:10---20
```
6. 输出变量的类型:
```python
x = 10
print(type(x)) # 输出:<class 'int'>
```
7. 将变量的值保存到文件中:
```python
x = 10
with open("output.txt", "w") as f:
print(x, file=f)
```
阅读全文