Python for loop用于迭代序列。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是iterable对象。我们可以使用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循环时,它被称为嵌套for循环。下面的代码显示了Python的嵌套循环。
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
输出
Python for loop with range()函数
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循环的continue语句
我们可以在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中对for循环使用else子句。else块仅在for循环未被break语句终止时执行。
假设我们有一个函数,当且仅当所有数字都是偶数时,我们有一个函数来打印数字之和。如果存在奇数,我们可以使用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
结论
Python中的for循环与其他编程语言非常相似。我们可以在for循环中使用break和continue语句来改变执行。然而,在Python中,我们也可以在for循环中使用可选的else块。