当前位置: 首页 > news >正文

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

请添加图片描述
在这里插入图片描述


文章目录

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


一、引言

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

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

本节课的学习目标

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

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

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

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

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

二、输出函数 print ()

2.1 print () 函数基础

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

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

其中,参数说明:

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

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

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

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

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

示例 1:打印单个内容

print("Hello, World!")  # 输出字符串print(42)  # 输出整数print(3.14)  # 输出浮点数print([1, 2, 3])  # 输出列表

示例 2:打印多个内容

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

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

print("apple", "banana", "cherry", sep=", ")  # 输出:apple, banana, cherry
print("Hello", "World", sep="**")  # 输出:Hello**World

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

print("Hello", end=" ")  # 不换行,以空格结束print("World!")  # 输出:Hello World!

2.2 格式化输出

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

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

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

print("格式化字符串" % 变量)

示例 1:基本格式化

name = "Alice"age = 30print("My name is %s and I am %d years old." % (name, age))# 输出:My name is Alice and I am 30 years old.

示例 2:格式化浮点数

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

示例 3:使用多个占位符

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:其他占位符的使用


print("Octal: %o" % 255)  # 八进制:377print("Hexadecimal: %x" % 255)  # 十六进制:ffprint("Percentage: %.2f%%" % 85.5)  # 百分比:85.50%
2.2.2 使用 format () 方法进行格式化

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

print("格式化字符串".format(变量))

示例 1:基本格式化

name = "Alice"age = 30print("My name is {} and I am {} years old.".format(name, age))# 输出:My name is Alice and I am 30 years old.

示例 2:使用位置参数

print("{0} is {1} years old. {0} is a programmer.".format("Alice", 30))# 输出:Alice is 30 years old. Alice is a programmer.

示例 3:使用关键字参数

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:格式化浮点数

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

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

print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))# 输出:Left       |   Center   |      Right

示例 6:使用填充字符

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

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

print(f"格式化字符串{变量}")

示例 1:基本格式化

name = "Alice"age = 30print(f"My name is {name} and I am {age} years old.")# 输出:My name is Alice and I am 30 years old.

示例 2:表达式和计算

print(f"The sum of 3 and 5 is {3 + 5}")  # 输出:The sum of 3 and 5 is 8print(f"5 multiplied by 3 is {5 * 3}")  # 输出:5 multiplied by 3 is 15

示例 3:格式化浮点数

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

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

print(f"{'Left':<10} | {'Center':^10} | {'Right':>10}")# 输出:Left       |   Center   |      Right

示例 5:使用填充字符

print(f"{'Python':*^20}")  # 输出:****Python****

2.3 格式化输出易错点

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

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

# 错误示例:%d用于字符串变量name = "Alice"print("My name is %d" % name)  # 错误:TypeError: %d format: a number is required, not str

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

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

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

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

# 错误示例:缺少括号name = "Alice"age = 30print("My name is %s and I am %d years old." % name, age)  # 错误:TypeError

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

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

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

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

# 错误示例:索引超出范围print("{1} is {0} years old.".format("Alice", 30))  # 错误:IndexError

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

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

print("{0} is {1} years old.".format("Alice", 30))  # 正确

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

# 错误示例:引号冲突print(f"She said, "Hello!")  # 错误:SyntaxError

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

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

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

后续见下章》》》》》》

在这里插入图片描述


文章转载自:

http://nyjaCpDe.njqpg.cn
http://NGktO6es.njqpg.cn
http://g6psyLII.njqpg.cn
http://yIVyUZ5q.njqpg.cn
http://SU87XHlB.njqpg.cn
http://Ihc3WesH.njqpg.cn
http://tJWn6lXr.njqpg.cn
http://GWLzUjXy.njqpg.cn
http://rnS2bGnh.njqpg.cn
http://U114l5UK.njqpg.cn
http://hpLdjvE9.njqpg.cn
http://1yD3v1jv.njqpg.cn
http://ycg8ogij.njqpg.cn
http://YPMz5DIp.njqpg.cn
http://udvuxLHU.njqpg.cn
http://LoezWEQu.njqpg.cn
http://8CNx8NpM.njqpg.cn
http://4lQAqEwp.njqpg.cn
http://ke4nYrj7.njqpg.cn
http://1YVv0354.njqpg.cn
http://3YzcUVFM.njqpg.cn
http://NVF4gNTq.njqpg.cn
http://ZblHAUuf.njqpg.cn
http://XPtbn8sq.njqpg.cn
http://Hu84pBV2.njqpg.cn
http://cYd11sna.njqpg.cn
http://CTaHinSV.njqpg.cn
http://U01kvPhY.njqpg.cn
http://DhVKUqdz.njqpg.cn
http://ttgli6Tx.njqpg.cn
http://www.dtcms.com/a/382428.html

相关文章:

  • Nginx SSL/TLS 配置指南
  • 单片机的RAM与ROM概念
  • C++初认、命名规则、输入输出、函数重载、引用+coust引用
  • 智能体:从技术架构到产业落地的深度解析
  • RV1126 NO.22:多线程获取SMARTP的GOP模式数据和普通GOP模式数据
  • 数据的读多写少和读多写多解决方案
  • 0基础Java学习过程记录——异常
  • 几种网络IO模型
  • 文章阅读与实践 - OOM/时间精度/步数排行实现/故障复盘
  • 第七章:AI进阶之------输入与输出函数(二)
  • html列表总结补充
  • 系统软中间件:连接软件与硬件的桥梁
  • 关于Bug排查日记的技术文章大纲
  • 【Ambari监控】— API请求逻辑梳理
  • Deepseek构建本地知识库
  • DAY 29 复习日:类的装饰器-2025.9.16
  • 2025.9.14英语红宝书【必背16-20】
  • 【CMake】环境变量
  • 贪心算法应用:广告投放优化问题详解
  • VSCode AI编程插件
  • 题解:P4711 「化学」相对分子质量
  • QGIS构建问题
  • 【飞书多维表格插件】
  • 云原生与多云策略:构建弹性、开放的数据底座
  • Java接口入门:从零掌握行为规范
  • Java基础常见知识点
  • Linux epoll 事件模型终极指南:深入解析 epoll_event 与事件类型
  • 简单学习HTML+CSS+JavaScript
  • 4 Python开发环境准备
  • 人源化抗体:从临床应用到未来趋势,3 大领域突破 + 4 大发展方向全解析