Python-For循环

时间:2020-02-23 14:42:09  来源:igfitidea点击:

在本教程中,我们将学习Python中的for循环。

我们在Python中使用for循环来遍历一个序列,该序列可以是字符串,列表,元组,集合或者字典。

for语法

以下是Python中for循环的语法。

for iterate_variable in sequence:
  #
  # body of the for loop
  #

在每次迭代中,都会从序列中获取一项并分配给iterate_variable。
然后执行for循环体内的代码。

字符串和for循环

我们可以使用" for"循环来遍历字符串中的字符并打印出字符。

在下面的Python程序中,我们列出了字符串的所有字符。

# string
str = 'Hello World'

for ch in str:
  print(ch)

print("End of code.")

上面的代码将打印以下输出。

H
e
l
l
o
 
W
o
r
l
d
End of code.

列表和for循环

我们可以使用" for"循环来遍历列表中的项目。

在下面的Python程序中,我们列出了列表中的所有项目。

# list
list = [1, 2, 3, 1, 3]

for item in list:
  print(item)

print("End of code.")

我们将获得以下输出。

1
2
3
1
3
End of code.

元组和for循环

我们可以使用" for"循环来遍历元组的项目。

在下面的Python代码中,我们将打印出元组的所有项目。

# tuple
tuple = ('theitroad', 9.1, True)

for item in tuple:
  print(item)

print("End of code.")

上面的代码将打印以下输出。

theitroad
9.1
True
End of code.

设置和循环

我们可以使用" for"循环来访问集合中的项目。

在下面的Python代码中,我们列出了集合中的所有项目。

# set
set = {1, 2, 3, 'Hello'}

for item in set:
  print(item)

print("End of code.")

我们将获得以下输出。

1
2
3
Hello
End of code.

字典和for循环

我们可以使用" for"循环来遍历字典的键值对。

在下面的示例中,我们列出了字典的所有键值对。

# dictionary
dictionary = {
    'name': 'theitroad',
    'score': 9.1,
    'isOnline': True
}

for key in dictionary:
  print(key, "=", dictionary[key])

print("End of code.")

上面的代码将打印以下结果。

name = theitroad
score = 9.1
isOnline = True
End of code.

使用字典时,我们将在每次迭代中获取字典的键。

为了获得特定键的值,我们使用dictionaryVariableName [key]

break语句

我们使用break语句跳出for循环。

在下面的Python程序中,我们将打印名称中出现的字母。
但是,一旦遇到任何元音(小写和大写),我们都将退出for循环。

name = 'theitroad'

for l in name:

    # check
    if l in "aeiouAEIOU":
        break

    # print
    print(l)

print("End of code.")

这将仅打印字母Y,因为第二个字母是元音之一,我们将退出for循环。

Y
End of code.

continue语句

我们使用" continue"语句来跳过迭代,并移至for循环序列中的下一项。

在下面的示例中,我们有一个名称,并在名称中打印字母。
但是我们跳过了所有的元音(小写和大写)。

name = 'Jane Doe'

for l in name:

    # check
    if l in "aeiouAEIOU":
        continue

    # print
    print(l)

print("End of code.")

我们将获得以下输出。

J
n
 
D
End of code.

range函数

函数range返回从0开始递增1的数字序列。

语法

以下是range()函数的语法。

range(start, stop, step)

其中,start是起始编号。
默认值为0。

stop是位置范围将停止但不包括的数字。

步骤是增量。
默认值为1。

如果我们想要一个序列" 0、1、2、3和4",我们将编写以下内容。

range(0, 5)

注意!我们正在编写5,因为range()将从起点开始并在停止处结束-1。

如果我们想要一个序列" 5、4、3、2和1",我们将编写以下内容。

range(5, 0, -1)

"for"中的" else"

带有" for"循环的" else"块包含在for循环结束之后执行的一段代码。

在下面的Python程序中,在for循环结束迭代序列中的项目之后,我们将获得" for循环结束"。

for i in range(1, 4):
  print(i)
else:
  print("End of for loop")

print("End of code.")