在 Python 中,输入和输出是编程中常见的操作,用于与用户交互或将程序结果展示出来。以下是一些关于 Python 输入和输出的基本概念和用法:

输出(print 函数):

使用 print 函数将信息输出到控制台:
name = "Alice"
age = 25
print("Name:", name, "Age:", age)

格式化字符串:

使用格式化字符串进行更灵活的输出:
name = "Bob"
age = 30
print("Name: {}, Age: {}".format(name, age))
# 或者使用 f-string(Python 3.6+)
print(f"Name: {name}, Age: {age}")

输入(input 函数):

使用 input 函数接收用户输入:
name = input("Enter your name: ")
print("Hello, " + name + "!")

文件操作:

写入文件:
with open("example.txt", "w") as file:
    file.write("Hello, World!")

读取文件:
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

输出重定向:

将输出重定向到文件:
with open("output.txt", "w") as f:
    print("This will be written to the file", file=f)

标准错误输出:
import sys

sys.stderr.write("This is an error message\n")

这些是一些基本的输入和输出操作。在实际应用中,你可能还会用到更高级的输入处理、格式化和文件操作等技术。在处理文件时,请确保使用适当的异常处理来处理文件可能引发的异常。


转载请注明出处:http://www.zyzy.cn/article/detail/13273/Python3