Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

10. Python For 循环语法

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块。