8.01 PY process control loop while the

8.01 PY process control loop while the

Cycle is an iterative process, we need to repeat doing a live person, the computer also need to repeat a live dry. ATM validation fails, the computer will enable us to once again enter the password. This time I have to tell us wile loops, while loops, also known as a conditional loop.

grammar

# 条件循环
while 条件
    代码块
# 永真循环
while True:
    代码块

The cycle has never really code block cyclic, so the introduction of the composition while + break

while + break

break off the circulation means terminates the current layer, other code execution.

while True:
    代码块1
    break  # 跳出while循环
代码块2 # break后代码块2正常运行

The following examples of the use of while + break with a landing system

while True:
    user = 'wzh'
    pwd = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user and pwd == inp_pwd:
        print('login successful')
        break
    else:
        print('username or password error')
print('while循环结束')

while + continue

means continue to terminate this cycle, the next cycle directly into

# 打印1-10中除了8的其他数
n = 1
while n <= 10:
    if n == 8: # 当n=8时,跳出本次循环,即不打印8
        continue
    print(n)
    n += 1

continue the code can not be added to the final step in the execution of the loop because the code to add the phrase is meaningless

while loop nested

ATM password success also requires a series of command operations, such as withdrawals, such as transfers. And after performing the operation function will exit the command function, i.e. the output to perform an input function q exit while loop function and exits the program ATM.

while True:
    user = 'wzh'
    pwd = '123'
    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user and pwd == 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 + else

else it will only execute code in else in the while not break.

# while+else
n = 1
while n < 3:
    print(n)
    n += 1
else:
    print('else会在while没有被break时才会执行else中的代码')

Guess you like

Origin www.cnblogs.com/dadazunzhe/p/11284712.html
Recommended