实现ATM的输入密码重新输入的功能
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')
else:
print('username or password error')
while + break 组合
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')
break
else:
print('username or password error')
print('退出了while循环')
while + continue (continue的意思是终止本次循环,直接进入下一次循环)
n = 1
while n<10:
if n == 8:
continue
print(n)
n += 1
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} 请输入你需要执行的命令:')
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循环')
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('退出了while循环')
print('退出了while循环')
# while+else
n = 1
while n < 3:
print(n)
n += 1
else:
print('else会在while没有被break时才会执行else中的代码'
'''
1
2
else会在while没有被break时才会执行else中的代码
'''
# for循环
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循环按照索引取值
name_list = ['nick', 'jason', 'tank', 'sean']
# for i in range(5): # 5是数的用法
# for i in range(1, 10): # range顾头不顾尾
for i in range(len(name_list)):
print(i, name_list[i])
#for+break
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
if name == 'jason':
break
print(name)
#for + continue
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
if name == 'jason':
continue
print(name)
"""
nick
tank
sean
"""
# 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
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(pycharm中里有优化机制,效果展现不出来,需在jupyter中运行)
import time
print('Loading', end='')
for i in range(6):
print(".", end='')
time.sleep(0.2)