python 基础之while无限循环

用户登录程序

username = "chenxi"
passwed = "testki"
counter = 0
while counter < 3: # 测试3次
    user = input("输入用户名:")
    passw = input("输入密码:")
    if user == username and passw == passwed :
        print("登录成功")
        break  #退出
    else:
        print("重新输入")
    counter += 1

  测试-1

D:pythonpython.exe D:/untitled/dir/for.py
输入用户名:bhghjb
输入密码:njbmnbm
重新输入
输入用户名:bhbjb
输入密码:nnbnbm
重新输入
输入用户名:nnbmnb
输入密码:jhjh
重新输入

Process finished with exit code 0

  测试-2

D:pythonpython.exe D:/untitled/dir/for.py
输入用户名:chenxi
输入密码:testki
登录成功

  打印0-9,小于5不打印

for i in range(10):
    if i < 5 :
        continue  # 结束本次循环
    print(i)

  测试

D:pythonpython.exe D:/untitled/dir/for.py
5
6
7
8
9

  打印双层循环

for i in range(10):
    print ("chenxi:",i)
    for j in range(10):
        print(j)

  测试

D:pythonpython.exe D:/untitled/dir/for.py
chenxi: 0
0
1
2
3
4
5
6
7
8
9
chenxi: 1
0
1
2
3
4
5
6
7
8
9
chenxi: 2
0
1
2
3
4
5
6
7
8
9
chenxi: 3
0
1
2
3
4
5
6
7
8
9
chenxi: 4
0
1
2
3
4
5
6
7
8
9
chenxi: 5
0
1
2
3
4
5
6
7
8
9
chenxi: 6
0
1
2
3
4
5
6
7
8
9
chenxi: 7
0
1
2
3
4
5
6
7
8
9
chenxi: 8
0
1
2
3
4
5
6
7
8
9
chenxi: 9
0
1
2
3
4
5
6
7
8
9

Process finished with exit code 0

  i小于5不循环

for i in range(10):
    if i < 5 :
        continue  # 结束本次循环
    print ("chenxi:",i)
    for j in range(10):
        print(j)

  测试

D:pythonpython.exe D:/untitled/dir/for.py
chenxi: 5
0
1
2
3
4
5
6
7
8
9
chenxi: 6
0
1
2
3
4
5
6
7
8
9
chenxi: 7
0
1
2
3
4
5
6
7
8
9
chenxi: 8
0
1
2
3
4
5
6
7
8
9
chenxi: 9
0
1
2
3
4
5
6
7
8
9

Process finished with exit code 0

  利用break当j=6时跳出本次循环体

for i in range(10):
    if i < 5 :
        continue  # 结束本次循环
    print ("chenxi:",i)
    for j in range(10):
        print(j)
        if j == 6 :
            break   #当j=6时跳出循环体

  测试

D:pythonpython.exe D:/untitled/dir/for.py
chenxi: 5
0
1
2
3
4
5
6
chenxi: 6
0
1
2
3
4
5
6
chenxi: 7
0
1
2
3
4
5
6
chenxi: 8
0
1
2
3
4
5
6
chenxi: 9
0
1
2
3
4
5
6

Process finished with exit code 0

  利用标志物位跳出多层循环

# 小于5 不打印
exit_flag = False   #设置exit_flag初始值
for i in range(10):
    if i < 5 :
        continue  # 结束本次循环
    print ("chenxi:",i)
    for j in range(10):
        print(j)
        if j == 6 :
            exit_flag = True# 当j = 6 时;修改exit_flag变量值为True
            break   #当j=6时跳出循环体
    if exit_flag: #判断exit_flag=True时,跳出第二层循环体
        break

  测试

D:pythonpython.exe D:/untitled/dir/for.py
chenxi: 5
0
1
2
3
4
5
6

  

草都可以从石头缝隙中长出来更可况你呢
原文地址:https://www.cnblogs.com/rdchenxi/p/11079009.html