Python for循环示例

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

Python for循环用于迭代序列。
for循环几乎存在于所有编程语言中。

Python for循环

我们可以使用for循环遍历列表,元组或者字符串。
for循环的语法为:

for itarator_variable in sequence_name:
	Statements
	. . .
	Statements

我们来看一些在Python程序中使用for循环的示例。

使用for循环打印字符串的每个字母

Python字符串是字符序列。
我们可以使用for循环遍历字符并打印出来。

word="anaconda"
for letter in word:
	print (letter)

输出:

a
n
a
c
o
n
d
a

遍历列表,元组

List和Tuple是可迭代的对象。
我们可以使用for循环遍历它们的元素。

words= ["Apple", "Banana", "Car", "Dolphin" ]
for word in words:
	print (word)

输出:

Apple
Banana
Car
Dolphin

让我们看一个示例,查找元组中的数字总和。

nums = (1, 2, 3, 4)

sum_nums = 0

for num in nums:
  sum_nums = sum_nums + num

print(f'Sum of numbers is {sum_nums}')

# Output
# Sum of numbers is 10

Python嵌套循环

当我们在另一个for循环中包含一个for循环时,称为嵌套for循环。
以下代码显示了Python中嵌套的for循环。

words= ["Apple", "Banana", "Car", "Dolphin" ]
for word in words:
      #This loop is fetching word from the list
      print ("The following lines will print each letters of "+word)
      for letter in word:
              #This loop is fetching letter for the word
              print (letter)
      print("") #This print is used to print a blank line

带有range()函数的Python for循环

Python range()是内置函数之一。
它与for循环一起使用,以运行特定次数的代码块。

for x in range(3):
  print("Printing:", x)
	
# Output

# Printing: 0
# Printing: 1
# Printing: 2

我们还可以为范围功能指定开始,停止和步进参数。

for n in range(1, 10, 3):
  print("Printing with step:", n)
	
# Output

# Printing with step: 1
# Printing with step: 4
# Printing with step: 7

带for循环的break语句

break语句用于过早退出for循环。
满足特定条件时,它用于中断for循环。

假设我们有一个数字列表,我们想检查一个数字是否存在。
我们可以遍历数字列表,如果找到了数字,请跳出循环,因为我们不需要继续遍历其余元素。

nums = [1, 2, 3, 4, 5, 6]

n = 2

found = False
for num in nums:
  if n == num:
      found = True
      break

print(f'List contains {n}: {found}')

# Output
# List contains 2: True

用for循环继续语句

我们可以在for循环内使用continue语句,以针对特定条件跳过for循环主体的执行。

假设我们有一个数字列表,并且希望打印正数之和。
我们可以使用continue语句跳过for循环中的负数。

nums = [1, 2, -3, 4, -5, 6]

sum_positives = 0

for num in nums:
  if num < 0:
      continue
  sum_positives += num

print(f'Sum of Positive Numbers: {sum_positives}')

带有可选else块的Python for循环

我们可以在Python中将else子句与for循环一起使用。
仅当for循环未由break语句终止时,才会执行else块。

假设我们有一个函数,当且仅当所有数字均为偶数时,才打印数字之和。
如果存在奇数,我们可以使用break语句终止for循环。
我们可以在else部分中打印总和,以便仅在正常执行for循环时才打印总和。

def print_sum_even_nums(even_nums):
  total = 0

  for x in even_nums:
      if x % 2 != 0:
          break

      total += x
  else:
      print("For loop executed normally")
      print(f'Sum of numbers {total}')

# this will print the sum
print_sum_even_nums([2, 4, 6, 8])

# this won't print the sum because of an odd number in the sequence
print_sum_even_nums([2, 4, 5, 8])

# Output

# For loop executed normally
# Sum of numbers 20