23. 循环结构之for循环

  我们已经学过了while循环,下面接着学习Python中的第二种循环机制——for循环。理论上,for循环能做的事情,while循环都可以做,但for循环的循环取值(遍历取值)操作比while循环简洁。不过,在实践for循环之前,需要介绍一下成员运算符和内置函数range。

成员运算符in和not in

  成员运算符用来验证给定的值(变量)在指定的范围里是否存在。成员运算符有两个,分别是in和not in。

print("he" in "hello")
print("he" not in "hello")
print("he" in "world")
print("he" not in "world")

运行结果为:

True
False
False
True

  代码分析:字符串"he"属于字符串"hello"的一部分,所以第一个成员运算表达式为真,not in是in的反逻辑,所以第二个成员运算表达式为假。字符串"he"不属于"world"的一部分,所以第三个成员运算表达式为假,自然第四个表达式为真。

range函数简介

  range函数顾名思义,代表了一个范围,通常带有一个或两个整型参数。例如,range(1, 10),它代表1~9这9个整数的范围(不包括10,这就是所谓的”顾头不顾尾“)。如果range中仅有1个参数,默认范围从0开始,如range(5),它的范围是0、1、2、3、4,下面通过代码进行验证。

print(1 in range(1, 10))
print(9 in range(1, 10))
print(10 in range(1, 10))
print(0 in range(5))

运行结果为:

True
True
False
True

for循环

  好了,终于轮到for登场了。看下面的例子:

for i in range(5):
    print("Hello world!")

运行结果为:

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

  可见,实现同样的功能,用for循环比while循环简洁了许多,下一节将对代码做具体的分析。

你可能感兴趣的:(Python入门)