1. 程式人生 > >Python三次登陸

Python三次登陸

空格 enter times input python實現 nbsp rip count you

題目:Python實現三次登陸

不要急於馬上把三次登陸寫出來,一定要將復雜的程序簡單化,必須一步一步地去擴展,這樣才保證不會出錯。

步驟一:實現簡單的一次登陸

# 事先定義
user = ‘dark_knight‘
pwd = ‘dk123‘

username = input(‘Please enter username:‘)
password = input(‘Please enter password:‘)

# 判斷
if username == user and password == pwd:
    print(‘Login successfully!‘)
else:
    print(‘Login failed!‘)

步驟二:實現簡單的三次登陸

# 事先定義
user = ‘dark_knight‘
pwd = ‘dk123‘
count = 1  # 定義次數

while True:
    if count == 4: # 大於3次則退出循環
        print(‘Too many times!‘)
        break
    username = input(‘Please enter username:‘)
    password = input(‘Please enter password:‘)

    # 判斷
    if username == user and password == pwd:
        print(‘Login successfully!‘)
        break
    else:
        print(‘Login failed!‘)

    count += 1   # 每次循環都次數都進行加1操作

  

步驟三:解決三次登陸中的BUG以及擴展三次登陸

1、去除字符串兩邊的空格

2、當用戶輸入None時則提示用戶反復輸入。

3、當用戶輸入的信息不匹配時則告訴用戶還有幾次機會。

# 事先定義
user = ‘dark_knight‘
pwd = ‘dk123‘
count = 1  # 定義次數

while True:
    if count == 4: # 大於3次則退出循環
        print(‘Too many times!‘)
        break
    username = input(‘Please enter username:‘).strip() # 去除字符串兩邊的空格
    password = input(‘Please enter password:‘).strip() # 去除字符串兩邊的空格

    # 當用戶輸入有值時
    if username and password:
        # 判斷
        if username == user and password == pwd:
            print(‘Login successfully!‘)
            break
        else:
            print(‘Login failed!‘)
            print(‘You have %s chance.‘%(3 - count))

    # 當用戶輸入None時
    else:
        print(‘You enter blank, please re-enter!‘)
        continue    # 當用戶輸入None時,跳出本次循環。

    count += 1   # 每次循環都次數都進行加1操作

  

Python三次登陸