Python 中的条件和循环

作者:Ruben Geert van den Berg,源自 SPSS Python 基础

  • Python “for” 循环
  • Python “while” 循环
  • Python “if” 语句
  • Python “if-else” 语句
  • Python “if-elif-else” 语句

条件、循环和函数是任何计算机语言的常见组成部分。在 Python 中,它们的结构非常相似,如下图所示。

Python For 循环结构

函数、循环或条件以冒号 : 结尾;
一个或多个_缩进_行表示它们受条件或循环的约束,或是某个函数的一部分;
一个_未缩进_的行表示某个循环、条件或函数已结束。

循环、条件和函数通常是嵌套的,如其缩进级别所示。下面的语法显示了一个带注释的示例。

***PYTHON CONDITION IN FOR LOOP EXAMPLE.  
**  
begin program python3.  
for ind in range(10):  # 循环开始
  print('What I know about {},'.format(ind))  # 受循环约束
  if(ind % 2 == 0):  # 条件开始
    print('is that it\'s an even number.')  # 受循环和条件约束
  else:  # 前一个条件结束,开始新的条件
    print('is that it\'s an odd number.')  # 受循环和条件约束
  print('That will do.')  # 条件结束,循环结束
end program.

现在让我们仔细看看 Python 中循环和条件的结构。

Python “for” 循环

在 Python 中,我们主要使用 for 循环来迭代一个 可迭代对象 (iterable object) 的所有元素。因为这非常简单明了,所以一个例子就足够了。

***PYTHON "FOR" LOOP EXAMPLE.  
**  
begin program python3.  
countries = ['Netherlands','Germany','France','Belgium','Slovakia','Bulgaria','Spain']  
for country in countries:  
  print(country)  
print("That's all.")  
end program.

注意,缩进表示循环在哪里结束:“That’s all.” 只打印一次,因为它没有缩进。

Python “while” 循环

第二种 Python 循环是 “while” 循环。只要满足某个条件,它就会一直迭代。请确保在某个时候条件不再满足,否则 Python 将永远循环下去——或者直到你以某种方式中断它,例如使用 Windows 的任务管理器。

我们在实践中很少使用 “while” 循环,但我还是给出一个例子:我们将随机抽取 0 和 1,只要 样本中 1 的数量小于 10。如果我们无限重复这个实验,样本大小将遵循负二项分布。

***ADD RANDOM ZEROES AND ONES TO SAMPLE AS LONG AS THERE'S FEWER THAN 10 ONES IN THE SAMPLE.  
**  
begin program python3.  
import random  
sample = []  
while sum(sample) < 10:  
  sample.append(random.randint(0,1))  
  print(sample)  
end program.  
  
***NOTE: SECOND/THIRD/... ATTEMPTS TYPICALLY RESULT IN SHORTER/LONGER LISTS.**

Python “if” 语句

Python 中的条件处理使用 if 语句完成,它们的工作方式与 forwhile 非常相似。让我们首先运行一个简单的例子。

***SIMPLE IF STATEMENT.  
**  
begin program python3.  
countries = ['Netherlands','Germany','France','Belgium','Slovakia','Bulgaria','Spain']  
for country in countries:  
  if 'm' in country:  
    print('%s contains the letter "m".'%country)  
end program.

Python “if-else” 语句

我们之前的例子在满足某个条件时执行了某些操作。如果条件不满足,则什么也不会发生。有时这正是我们需要的。但在其他情况下,我们可能希望在条件满足时执行某些操作。我们可以使用 else 来做到这一点,如下所示。

***IF AND ELSE EXAMPLE.  
**  
begin program python3.  
countries = ['Netherlands','Poland','Germany','Portugal','France','Belgium','Slovakia','Bulgaria','Spain']  
for country in countries:  
  if country.startswith("S"):  
    print('%s starts with an "S".'%country)  
  else:  
    print('%s doesn\'t start with an "S".'%country)  
end program.

Python “if-elif-else” 语句

我们的最后一个例子处理了两种选择:满足条件或不满足条件。我们可以使用 elif 添加更多选项,它是 “else if” 的缩写。这意味着满足某个条件并且我们的 if 结构中没有满足之前的任何条件。

因此,一个 if 结构可能包含(在相同的缩进级别):

  • 1 个 if 子句 (clause):如果满足某个条件,则执行某些操作;
  • 0 个或多个 elif 语句 (statement):如果满足某个条件,但没有满足之前的任何条件,则执行某些操作;
  • 0 个或 1 个 else 语句:如果之前的任何条件都不满足,则执行某些操作。

示例

***IF, ELIF AND ELSE EXAMPLE.  
**  
begin program python3.  
countries = ['Netherlands','Poland','Germany','Portugal','France','Belgium','Slovakia','Bulgaria','Spain']  
for country in countries:  
  if country.startswith("S"):  
    print('%s starts with an "S".'%country)  
  elif country.startswith("P"):  
    print('%s starts with a "P".'%country)  
  else:  
    print('%s doesn\'t start with a "P" or an "S".'%country)  
end program.