Python3 输入和输出详解
                           
天天向上
发布: 2025-03-14 23:00:10

原创
353 人浏览过

在 Python 中,输入输出是与用户交互和处理数据的核心部分。Python 提供了多种方式来处理输入输出(I/O)操作,下面我们详细讲解 Python3 中的输入和输出操作。


1. 输出(Print)

在 Python 中,输出通常是通过 print() 函数来实现的。它将指定的内容输出到标准输出设备(通常是屏幕)。

基本用法:

print("Hello, World!")

这会在屏幕上打印:

Hello, World!

打印多个值:

你可以在 print() 函数中传递多个值,它们会自动用空格隔开:

a = 10
b = 20
print(a, b)  # 输出: 10 20

打印不换行:

默认情况下,print() 函数在输出内容后会换行。如果你不希望换行,可以通过 end 参数来控制:

print("Hello", end=" ")
print("World!")  # 输出: Hello World!

格式化输出:

  1. 使用 f-string(推荐方法,Python 3.6 及以上) f-string 是 Python 3.6 引入的一个非常简洁且高效的字符串格式化方法。通过在字符串前加 f,可以直接在字符串中嵌入表达式。
   name = "Alice"
   age = 25
   print(f"My name is {name} and I am {age} years old.")  # 输出: My name is Alice and I am 25 years old.
  1. 使用 format() 方法 在 Python 3 中,str.format() 方法可以格式化字符串。你可以在字符串中放置花括号 {},然后用 format() 方法填充它们。
   name = "Bob"
   age = 30
   print("My name is {} and I am {} years old.".format(name, age))  # 输出: My name is Bob and I am 30 years old.
  1. 百分号 % 格式化 传统的格式化方法,通过 % 来指定类型和位置:
   name = "Charlie"
   age = 35
   print("My name is %s and I am %d years old." % (name, age))  # 输出: My name is Charlie and I am 35 years old.

2. 输入(Input)

在 Python 中,获取用户输入通常通过 input() 函数实现。它允许从控制台读取一行输入,返回输入的内容。

基本用法:

user_input = input("Enter your name: ")
print(f"Hello, {user_input}!")

当你运行上述代码时,程序会提示用户输入名字,输入后返回并打印问候语。

输入的类型:

需要注意的是,input() 函数接收的输入始终是字符串类型。如果需要将其转换为其他数据类型(如整数或浮点数),则需要手动进行类型转换。

age = input("Enter your age: ")
age = int(age)  # 将字符串转换为整数
print(f"You are {age} years old.")

或者,可以在 input() 语句中直接进行类型转换:

age = int(input("Enter your age: "))

处理异常输入:

用户输入的数据可能不符合预期类型,因此在处理输入时通常需要考虑异常处理。可以使用 try-except 块来捕捉转换错误。

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("Invalid input! Please enter a valid number.")

3. 文件输入输出(File I/O)

除了控制台的输入输出,Python 还提供了对文件的读写支持。文件 I/O 操作主要使用 open() 函数打开文件,并返回一个文件对象,通过这个对象可以对文件进行读写。

打开文件:

file = open("example.txt", "w")  # 打开文件用于写操作(如果文件不存在,创建文件)
file.write("Hello, file!")  # 写入内容
file.close()  # 关闭文件

文件的读操作:

file = open("example.txt", "r")  # 以读模式打开文件
content = file.read()  # 读取文件的所有内容
print(content)
file.close()

常用的文件打开模式:

  • "r":只读模式,文件必须存在。
  • "w":写入模式,若文件不存在则创建文件,若文件存在则覆盖文件内容。
  • "a":追加模式,若文件存在,则内容会被追加到文件末尾。
  • "b":二进制模式,用于处理非文本文件(如图片、视频等)。
  • "rb", "wb":二进制读写模式。

逐行读取文件:

file = open("example.txt", "r")
for line in file:
    print(line.strip())  # strip() 用于去除行尾的换行符
file.close()

文件操作的上下文管理器(推荐使用 with

使用 with 语句可以简化文件操作,它会自动在操作完成后关闭文件,避免出现忘记关闭文件的问题。

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

4. 总结

  • 输出:Python 使用 print() 函数输出内容,可以格式化字符串并控制输出的方式(如不换行)。
  • 输入:通过 input() 函数从用户获取输入,默认返回字符串,可以进行类型转换。
  • 文件 I/O:通过 open() 函数打开文件,可以进行读取、写入操作,建议使用 with 语句进行文件操作,确保文件在操作完成后正确关闭。

更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *