在编写 Python 程序时,输出语句和条件语句是两个非常基础但又十分重要的概念。输出语句用于显示程序执行的结果,而条件语句则是用于实现程序的逻辑判断,使代码具有不同的执行路径。
在 Python 中,最常用的输出语句是 print() 函数。它用于向控制台打印输出内容,常用于调试或展示程序的结果。
最简单的输出是直接传递字符串或变量到 print() 函数:
# 输出字符串
print("Hello, Python!")
# 输出变量
name = "Alice"
print(name)运行结果:
Hello, Python!
Alice为了更加灵活地输出内容,Python 提供了多种字符串格式化的方法,其中常见的有以下几种:
+ 连接字符串name = "Alice"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")运行结果:
My name is Alice and I am 25 years old.注意:要把整数
age用str()转换为字符串后才能与其他字符串拼接。
% 占位符name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))运行结果:
My name is Alice and I am 25 years old.%s 用于表示字符串,%d 用于表示整数。你可以通过这种方式将不同类型的变量插入到字符串中。
str.format()name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))运行结果:
My name is Alice and I am 25 years old.{} 是占位符,format() 方法会将参数按顺序填入占位符中。
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.f-string 是 Python 3.6 之后引入的功能,它使得字符串插值更加简洁和易读。
条件语句用于根据某些条件的真或假来决定程序执行哪个代码块。Python 使用 if 语句来实现条件控制。
if 语句会在条件为真时执行代码块。基本的 if 语句结构如下:
age = 18
if age >= 18:
print("You are an adult.")运行结果:
You are an adult.在这个例子中,age >= 18 为真,Python 执行 print("You are an adult.")。注意缩进:Python 使用缩进来区分代码块。
如果条件不成立,你可以使用 else 来定义另一种执行路径:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")运行结果:
You are a minor.这里,age = 16 不满足 age >= 18 的条件,因此执行 else 块中的语句。
当有多个条件需要判断时,使用 elif 来增加额外的判断条件:
score = 85
if score >= 90:
print("You got an A.")
elif score >= 80:
print("You got a B.")
elif score >= 70:
print("You got a C.")
else:
print("You need to improve.")运行结果:
You got a B.在这个例子中,score = 85 满足 score >= 80 的条件,因此执行 elif 块中的语句。
你可以在条件语句中嵌套其他条件语句,实现更复杂的逻辑控制:
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("You are allowed to enter.")
else:
print("You need a ticket to enter.")
else:
print("You are too young to enter.")运行结果:
You are allowed to enter.在这个例子中,首先检查 age >= 18,如果为真,再检查是否有票 has_ticket,根据不同条件输出相应的结果。
Python 还提供了简洁的条件表达式,也叫三元表达式,用来在一行内进行条件判断:
age = 20
message = "Adult" if age >= 18 else "Minor"
print(message)运行结果:
Adult这种写法简化了 if-else 语句,非常适合简单的条件判断。
通过本文的讲解,我们了解了 Python 中常用的输出语句和条件语句。print() 函数是输出结果的主要方式,而通过各种格式化方法,输出可以更加灵活和美观。条件语句是实现程序逻辑判断的核心,掌握 if、if-else 和 if-elif-else 的用法能够帮助我们更好地控制程序的执行流程。
在实际编程中,条件语句与输出语句常常结合使用,以实现复杂的交互功能。掌握这两个基础概念是写好 Python 程序的关键。