首页 > 代码库 > for 循环

for 循环

1.

for i in range(10): #i是临时变量,range(10)表示从0-9
    print(loop, i)

运行结果:

loop 0
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
2.

for i in range(0, 10, 2): # 其中的2表示步长,也就是隔一个数
    print(loop, i)

运行结果:
loop 0
loop 2
loop 4
loop 6
loop 8

3. 循环套循环

for i in range(10):
    print(--------,i)
    for j in range(10):
        print(j)
        if j> 5:
            break

运行结果:
-------- 0
0
1
2
3
4
5
6
-------- 1
0
1
2
3
4
5
6

一直到 i为9时

4. break是结束循环。continue是跳出本次循环,进入下一次循环

功能:用户登录,最多可登录三次

import getpass
_username = dmr
_password = 123
for i in range(3):
    username = input(username:)
    password = getpass.getpass(password:)
    if username == _username and password == _password:
        print(Welcome user {name} login....format(name=username))
        break
    else:
        continue
else:    
    print(invalid username and password)

 

for 循环