第七章:AI进阶之------输入与输出函数(一)



文章目录

    • 一、引言
    • [二、输出函数 print ()](#二、输出函数 print ())
      • [2.1 print () 函数基础](#2.1 print () 函数基础)
      • [2.2 格式化输出](#2.2 格式化输出)
        • [2.2.1 使用 % 占位符进行格式化](#2.2.1 使用 % 占位符进行格式化)
        • [2.2.2 使用 format () 方法进行格式化](#2.2.2 使用 format () 方法进行格式化)
        • [2.2.3 使用 f-strings 进行格式化(Python 3.6+)](#2.2.3 使用 f-strings 进行格式化(Python 3.6+))
      • [2.3 格式化输出易错点](#2.3 格式化输出易错点)
    • 后续见下章》》》》》》

一、引言

欢迎来到 Python 输入与输出函数的课程!在之前的课程中,我们已经学习了 Python 的基本数据类型、变量与赋值语句。今天,我们将学习如何与用户进行交互,通过输入函数获取用户的输入,以及通过输出函数向用户展示结果。

在 Python 编程中,输入输出(I/O)是程序与用户交互的基础。通过输入函数,程序可以接收用户的输入数据;通过输出函数,程序可以向用户展示处理结果。掌握输入输出函数的使用,是编写交互式程序的关键。

本节课的学习目标

  1. 掌握 print () 函数的使用,包括打印单个 / 多个内容、格式化输出

  2. 掌握 input () 函数的使用,包括获取用户输入和输入内容的类型转换

  3. 能够编写简单的交互式程序,处理用户输入并输出结果

  4. 理解并避免输入输出函数使用过程中的常见错误

现在,让我们开始今天的学习!

二、输出函数 print ()

2.1 print () 函数基础

在 Python 中,print () 函数是最常用的输出函数,用于向控制台输出文本信息。它的基本语法如下:

python 复制代码
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

其中,参数说明:

  • objects:要打印的一个或多个对象,可以是字符串、数字、列表等任何可打印的数据类型

  • sep:分隔符,用于分隔多个对象,默认值为一个空格

  • end:结束符,用于指定打印结束后添加的字符,默认值为换行符 '\n'

  • file:输出目标,可以是文件对象或标准输出(默认值为 sys.stdout)

  • flush:是否立即刷新缓冲区,默认值为 False

示例 1:打印单个内容

python 复制代码
print("Hello, World!")  # 输出字符串

print(42)  # 输出整数

print(3.14)  # 输出浮点数

print([1, 2, 3])  # 输出列表

示例 2:打印多个内容

python 复制代码
print("My name is", "Alice")  # 输出:My name is Alice

print("The sum of 3 and 5 is", 3 + 5)  # 输出:The sum of 3 and 5 is 8

示例 3:使用 sep 参数自定义分隔符

python 复制代码
print("apple", "banana", "cherry", sep=", ")  # 输出:apple, banana, cherry
print("Hello", "World", sep="**")  # 输出:Hello**World

示例 4:使用 end 参数自定义结束符

python 复制代码
print("Hello", end=" ")  # 不换行,以空格结束

print("World!")  # 输出:Hello World!

2.2 格式化输出

在实际应用中,我们经常需要将变量的值插入到字符串中,形成具有一定格式的输出。Python 提供了多种格式化输出的方式,包括 % 占位符、format () 方法和 f-strings。

2.2.1 使用 % 占位符进行格式化

% 占位符是 Python 中较早期的格式化方法,类似于 C 语言中的 printf 函数。其基本语法如下:

python 复制代码
print("格式化字符串" % 变量)

示例 1:基本格式化

python 复制代码
name = "Alice"

age = 30

print("My name is %s and I am %d years old." % (name, age))

# 输出:My name is Alice and I am 30 years old.

示例 2:格式化浮点数

python 复制代码
pi = 3.1415926535

print("Pi is approximately %.2f" % pi)  # 输出:Pi is approximately 3.14

示例 3:使用多个占位符

python 复制代码
print("The sum of %d and %d is %d." % (3, 5, 8))

# 输出:The sum of 3 and 5 is 8.

常用的 % 占位符

占位符 说明
%s 字符串
%d 整数
%f 浮点数
%x/%X 十六进制数
%o 八进制数
%% 百分号本身

示例 4:其他占位符的使用

python 复制代码
print("Octal: %o" % 255)  # 八进制:377

print("Hexadecimal: %x" % 255)  # 十六进制:ff

print("Percentage: %.2f%%" % 85.5)  # 百分比:85.50%
2.2.2 使用 format () 方法进行格式化

format () 方法是 Python 2.6 及以上版本引入的格式化方法,比 % 占位符更加灵活和强大。其基本语法如下:

python 复制代码
print("格式化字符串".format(变量))

示例 1:基本格式化

python 复制代码
name = "Alice"

age = 30

print("My name is {} and I am {} years old.".format(name, age))

# 输出:My name is Alice and I am 30 years old.

示例 2:使用位置参数

python 复制代码
print("{0} is {1} years old. {0} is a programmer.".format("Alice", 30))

# 输出:Alice is 30 years old. Alice is a programmer.

示例 3:使用关键字参数

python 复制代码
print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))

# 输出:My name is Alice and I am 30 years old.

示例 4:格式化浮点数

python 复制代码
pi = 3.1415926535

print("Pi is approximately {:.2f}".format(pi))  # 输出:Pi is approximately 3.14

示例 5:指定字段宽度和对齐方式

python 复制代码
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))

# 输出:Left       |   Center   |      Right

示例 6:使用填充字符

python 复制代码
print("{:*^20}".format("Python"))  # 输出:****Python****
2.2.3 使用 f-strings 进行格式化(Python 3.6+)

f-strings 是 Python 3.6 及以上版本引入的一种新的格式化方法,它简洁、高效且易于阅读,是目前推荐使用的格式化方式。其基本语法如下:

python 复制代码
print(f"格式化字符串{变量}")

示例 1:基本格式化

python 复制代码
name = "Alice"

age = 30

print(f"My name is {name} and I am {age} years old.")

# 输出:My name is Alice and I am 30 years old.

示例 2:表达式和计算

python 复制代码
print(f"The sum of 3 and 5 is {3 + 5}")  # 输出:The sum of 3 and 5 is 8

print(f"5 multiplied by 3 is {5 * 3}")  # 输出:5 multiplied by 3 is 15

示例 3:格式化浮点数

python 复制代码
pi = 3.1415926535

print(f"Pi is approximately {pi:.2f}")  # 输出:Pi is approximately 3.14

示例 4:指定字段宽度和对齐方式

python 复制代码
print(f"{'Left':<10} | {'Center':^10} | {'Right':>10}")

# 输出:Left       |   Center   |      Right

示例 5:使用填充字符

python 复制代码
print(f"{'Python':*^20}")  # 输出:****Python****

2.3 格式化输出易错点

在使用格式化输出时,初学者容易犯以下错误:

错误 1:占位符类型与变量类型不匹配

python 复制代码
# 错误示例:%d用于字符串变量

name = "Alice"

print("My name is %d" % name)  # 错误:TypeError: %d format: a number is required, not str

错误原因:% d 占位符需要整数类型,而变量 name 是字符串类型。

解决方案:使用正确的占位符类型:

python 复制代码
name = "Alice"

print("My name is %s" % name)  # 正确:使用%s占位符

错误 2:忘记使用元组包裹多个变量

python 复制代码
# 错误示例:缺少括号

name = "Alice"

age = 30

print("My name is %s and I am %d years old." % name, age)  # 错误:TypeError

错误原因:当使用多个变量时,必须用元组包裹。

解决方案:使用括号包裹多个变量:

python 复制代码
print("My name is %s and I am %d years old." % (name, age))  # 正确

错误 3:在 format () 方法中使用错误的索引

python 复制代码
# 错误示例:索引超出范围

print("{1} is {0} years old.".format("Alice", 30))  # 错误:IndexError

错误原因:索引从 0 开始,所以第一个参数是 {0},第二个是 {1}。

解决方案:正确使用索引:

python 复制代码
print("{0} is {1} years old.".format("Alice", 30))  # 正确

错误 4:在 f-string 中错误地使用引号

python 复制代码
# 错误示例:引号冲突

print(f"She said, "Hello!")  # 错误:SyntaxError

错误原因:f-string 中的引号与字符串中的引号冲突。

解决方案:使用不同类型的引号:

python 复制代码
print(f'She said, "Hello!"')  # 正确

print(f"She said, 'Hello!'")  # 正确

后续见下章》》》》》》

相关推荐
精益数智工坊几秒前
红牌作战是什么?红牌作战的实施步骤与核心要点
大数据·运维·前端·人工智能·精益工程
forEverPlume7 分钟前
c++如何通过解析二进制包头信息解决Socket传输过程中的粘包问题【详解】
jvm·数据库·python
玉小格14 分钟前
对py作业的一个复盘
开发语言·python
BU摆烂会噶14 分钟前
【LangGraph 持久化】让 AI Agent 拥有“记忆”
数据库·人工智能·python·langchain
Rust研习社14 分钟前
使用 Tonic 构建高性能异步 gRPC 服务
开发语言·网络·后端·http·rust
captain37617 分钟前
JDBC(Java Data Base Connectivity)
java·开发语言
冰西瓜60018 分钟前
深度学习的数学原理(三十)—— Transformer的子层连接:残差+层归一化
人工智能·深度学习·transformer
β添砖java18 分钟前
深度学习(6)softmax回归、损失函数、分类
人工智能·深度学习·回归
GISer_Jing19 分钟前
前端视角:B端传统配置化现状与AI冲击趋势
前端·人工智能·ai编程
南境十里·墨染春水24 分钟前
C++笔记 STL——vector
开发语言·c++·笔记