目录
Python是一种流行的编程语言,它有很多特性和优点。其中之一就是它的控制流语句,它可以让程序根据不同的条件或循环执行不同的操作。在这篇文章中,我们将介绍两种常用的控制流语句:if-else和for循环。
if-else 语句
if-else 语句是一种条件判断语句,它可以让程序根据一个或多个条件执行不同的代码块。if-else语句的基本结构如下:
if condition:
# do something if condition is True
else:
# do something else if condition is False
其中,condition是一个布尔表达式,它可以是一个变量,一个比较运算符(如==, !=, <, >等),一个逻辑运算符(如and, or, not等),或者它们的组合。如果condition为True,则执行if后面缩进的代码块;如果condition为False,则执行else后面缩进的代码块。
例如,我们可以用 if-else 语句来判断一个数是否为偶数:
num = int(input("Enter a number: ")) # get a number from user input
if num % 2 == 0: # use the modulo operator to check if the number is divisible by 2
print(num, "is an even number.") # print a message if the condition is True
else:
print(num, "is an odd number.") # print another message if the condition is False
我们也可以用 elif 关键字来添加更多的条件分支:
score = int(input("Enter your score: ")) # get a score from user input
if score >= 90: # check if the score is greater than or equal to 90
grade = "A" # assign a grade accordingly
elif score >= 80: # check if the score is greater than or equal to 80 and less than 90
grade = "B" # assign another grade accordingly
elif score >= 70: # check if the score is greater than or equal to 70 and less than 80
grade = "C" # assign another grade accordingly
elif score >= 60: # check if the score is greater than or equal to 60 and less than 70
grade = "D" # assign another grade accordingly
else: # for any other cases that do not match the above conditions
grade = "F" # assign another grade accordingly
print("Your grade is", grade) # print the result
for 循环
for循环是一种迭代语句,它可以让程序重复执行某个代码块,直到遍历完一个可迭代对象。可迭代对象可以是一个序列(如字符串,列表,元组等),一个集合(如集合,字典等),或者一个生成器(如range()函数等)。for循环的基本结构如下:
for item in iterable:
# do something with item
其中,item是一个临时变量,它会依次取iterable中的每个元素;iterable是一个可迭代对象;do something with item是要重复执行的代码块。
例如,我们可以用for循环来打印出一个列表中的所有元素:
fruits = ["apple", "banana", "cherry"] # define a list of fruits
for fruit in fruits:
print(fruit)
我们也可以用break关键字来提前结束循环;或者用continue关键字来跳过当前循环;或者用else关键字来在循环正常结束后执行额外的操作。
例如,我们可以用for循环和break关键字来查找一个列表中是否存在某个元素:
numbers = [1, 2, 3, 4, 5] # define a list of numbers
target = 6 # define a target number to search for
for number in numbers: # loop through the list of numbers
if number == target: # check if the current number is equal to the target
print(target, "is in the list.") # print a message if found
break # exit the loop
else: # if the loop ends without breaking
print(target, "is not in the list.") # print another message
总结
在这篇文章中,我们介绍了两种常用的Python控制流语句:if-else和for循环。它们可以让程序根据不同的条件或循环执行不同的操作。
参考文档
PS:
本文首发于公众号: 程序熵, 更多精彩文章请点击关注 code-shang