014控制流if、while 、for...in

时间:2019-10-24
本文章向大家介绍014控制流if、while 、for...in,主要包括014控制流if、while 、for...in使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

控制流


if语句

while

for...in

1、if语句


如果语句用来检查一个条件,如果条件为真则执行一个语句块(被称为if块),则执行另一个语句块(被称为else块)。

其中else分支是任选的

if boolean_expression1:
    suite1
elif boolean_expression2:
    suite2
elif boolean_expression3:
    suite3
else:
    else_suite

Example:

number = 23
guess = int(input('Enter an integer : '))
if guess == number:
    print('Congratulations, you guessed it.') # 新块开始处
    print('(but you do not win any prizes!)') # 新块结束处
elif guess < number:
    print('No, it is a little higher than that') # 另一个块
    # 你可以在一个块里做任何你想做的。。。
else:
    print('No, it is a little lower than that')
    # 只有guess > number 才会执行到此处
print('Done')

输出

$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done

$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done

$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

这里我们使用的是elif分支,事实上它把两个相关的if else-if else语句组合成一个if-elif-else语句。这样做不仅使得程序更加简洁也降低了缩进数量。

注意到if语句的结尾包含一个冒号: – 它指示其后将跟随一个语句块。同样,elifelse语句 必须在逻辑行的结尾写上冒号 ,其后是与之对应的语句块(当然还要有相应的缩进)

最后你也可以在if语句中插入另一个if-block块,这叫做嵌套的if语句

小技巧:如果需要考虑某个特殊的情况,但又不需要在这种情况发生时进行处理,那么可以使用pass作为该分支的块,表示一个空语句块。)。

可以有零个或多个 elif 部分,以及一个可选的 else 部分。 关键字 'elif' 是 'else if' 的缩写,适合用于避免过多的缩进。 一个 if ... elif ... elif ... 序列可以看作是其他语言中的 switchcase 语句的替代。

2、while 循环


循环就是一个重复的过程,我们人需要重复干一个活,那么计算机也需要重复干一个活。ATM验证失败,那么计算机会让我们再一次输入密码。这个时候就得说出我们的wile循环,while循环又称为条件循环。

while 条件
    code 1
    code 2
    code 3
    ...

while True:
    print('*1'*100)
    print('*2'*100)
# 实现ATM的输入密码重新输入的功能
while True:
    user_db = 'reed'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
    else:
        print('username or password error')

上述代码虽然实现了功能,但是用户密码输对了,他也会继续输入。

While+break


break的意思是终止掉当前层的循环,执行其他代码。

>>> while True:
...    print('1')
...    print('2')
...    break
...    print('3')
1
2

上述代码的break毫无意义,循环的目的是为了让计算机和人一样工作,循环处理事情,而他直接打印1和2之后就退出循环了。而我们展示下有意义的while+break代码的组合。

 while True:
    user_db = 'reed'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        break
    else:
        print('username or password error')

print('退出了while循环')

输出结果:

username: reed
password: 123
login successful
退出了while循环

While+Continue


continue的意思是终止本次循环,直接进入下一次循环

>>>n = 1
>>>while n < 4:
...    print(n)
...    n += 1
1
2
3
n = 1
while n < 10:
    if n == 8:
        # n += 1  # 如果注释这一行,则会进入死循环
        continue
    print(n)
    n += 1

continue不能加在循环体的最后一步执行的代码,因为代码加上去毫无意义,如下所示的

continue所在的位置就是毫无意义的。ps:注意是最后一步执行的代码,而不是最后一行。

while True:
    if 条件1:
        code1
        code2
        code3
        ...
    else:
        code1
        code2
        code3
        ...

    continue

while循环的嵌套


ATM密码输入成功还需要进行一系列的命令操作,比如取款,比如转账。并且在执行功能结束后会退出命令操作的功能,即在功能出执行输入q会退出输出功能的while循环并且退出ATM程序。

# 退出内层循环的while循环嵌套
while True:
    user_db = 'nick'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')

        while True:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                break
            print(f'{cmd} 功能执行')
    else:
        print('username or password error')

print('退出了while循环')
# 退出双层循环的while循环嵌套
while True:
    user_db = 'nick'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')

        while True:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                break
            print(f'{cmd} 功能执行')
        break###
    else:
        print('username or password error')

print('退出了while循环')

输出结果:

#退出双层结果
username: nick
password: 123
login successful
请输入你需要的命令:q
退出了while循环

布尔变量控制循环退出

# tag控制循环退出(定义布尔类型)
tag = True
while tag:
    user_db = 'nick'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')

        while tag:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                tag = False
            print(f'{cmd} 功能执行')
    else:
        print('username or password error')

print('退出了while循环')

输出结果:

username: nick
password: 123
login successful
请输入你需要的命令:q
q 功能执行
退出了while循环

while + else


else会在while没有被break时才会执行else中的代码(记住,while循环可以拥有else分支)

# while+else
n = 1
while n < 3:
    print(n)
    n += 1
    #不信的话你在此处加个break
else:
    print('else会在while没有被break时才会执行else中的代码')

输出结果:

1
2
else会在while没有被break时才会执行else中的代码

3、for…in 语句


for…in是另一种循环语句,用来遍历序列对象,也就是说遍历序列中的每个元素。

为什么有了while循环,还需要有for循环呢?不都是循环吗?我给大家出个问题,我给出一个列表,我们把这个列表里面的所有名字取出来。

name_list = ['nick', 'jason', 'tank', 'sean']

n = 0
while n < 4:
    # while n < len(name_list):
    print(name_list[n])
    n += 1
 ###输出如下:
nick
jason
tank
sean

字典也有取多个值的需求,字典可能有while循环无法使用了,这个时候可以使用我们的for...in循环。

info = {'name': 'nick', 'age': 19}

for item in info:
    # 取出info的keys
    print(item)
###输出结果:
name
age
name_list = ['nick', 'jason', 'tank', 'sean']
for item in name_list:
    print(item)
###输出结果:
nick
jason
tank
sean

for循环的循环次数受限于容器类型的长度,而while循环的循环次数需要自己控制。for循环也可以按照索引取值。

>>> print(list(range(1, 10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(1, 10):  # range顾头不顾尾
...    print(i)
1
2
3
4
5
6
7
8
9
# for循环按照索引取值
>>> name_list = ['nick', 'jason', 'tank', 'sean']
# for i in range(5):  # IndexError: list index out of range列表长度为4,输入5越界了
>>> for i in range(len(name_list)):
>>>    print(i, name_list[i])
0 nick
1 jason
2 tank
3 sean

for + break

for循环跳出本层循环。

# for+break
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    if name == 'jason':
        break
    print(name)
###输出结果
nick

for + continue

for循环调出本次循环,进入下一次循环

# for+continue
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    if name == 'jason':
        continue
    print(name)
##输出结果
nick
tank
sean

for + 循环嵌套

外层循环循环一次,内层循环循环所有的。

# for循环嵌套
for i in range(3):
    print(f'-----:{i}')
    for j in range(2):
        print(f'*****:{j}')
##输出结果:
-----:0
*****:0
*****:1
-----:1
*****:0
*****:1
-----:2
*****:0
*****:1

for+else

for循环没有break的时候触发else内部代码块。

# for+else
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    print(name)
else:
    print('for循环没有被break中断掉')
###输出结果:
nick
jason
tank
sean
for循环没有break中断掉

for循环实现loading


import time

print('Loading', end='')
for i in range(6):
    print(".", end='')
    time.sleep(0.2)
#输出结果:
Loading......

Range()函数


如果你确实需要遍历一个数字序列,内置函数 range() 会派上用场。它生成算术级数:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

给定的终止数值并不在要生成的序列里;range(10) 会生成10个值,并且是以合法的索引生成一个长度为10的序列。range也可以以另一个数字开头,或者以指定的幅度增加(甚至是负数;有时这也被叫做 '步进')

range(5, 10)
   5, 6, 7, 8, 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

要以序列的索引来迭代,您可以将 range()len() 组合如下:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

然而,在大多数这类情况下,使用 enumerate() 函数比较方便,请参见 循环的技巧

如果你只打印 range,会出现奇怪的结果:

>>> print(range(10))
range(0, 10)

range() 所返回的对象在许多方面表现得像一个列表,但实际上却并不是。此对象会在你迭代它时基于所希望的序列返回连续的项,但它没有真正生成列表,这样就能节省空间。

原文地址:https://www.cnblogs.com/FirstReed/p/11734655.html