學(xué)習(xí)自《編程小白的第一本 Python 入門書》
P61
驗(yàn)證用戶登錄的函數(shù)
def account_login():
password = input('Password:')
if password == '12345':
print('Login success!')
else:
print('Wrong password or invalid input!')
account_login()
account_login()
上面的函數(shù)可以改成這樣
def account_login():
password = input('Password:')
password_correct = password == '12345'
if password_correct:
print('Login success')
else:
print('Wrong password or invalid input!')
account_login()
account_login()
接下來(lái)使用elif語(yǔ)句給剛才設(shè)計(jì)的函數(shù)增加一個(gè)重置密碼的功能
password_list = ['*#*#','12345']
def account_login():
password = input('Password:')
password_correct = password == password_list[-1]
password_reset = password == password_list[0]
if password_correct:
print('Login success!')
elif password_reset:
new_password = input('Enter a new password:')
password_list.append(new_password)
print('Your password has changed successfully!')
account_login()
else:
print('Wrong password or invalid input!')
account_login()
account_login()
第1行:創(chuàng)建一個(gè)列表,用于存儲(chǔ)用戶的密碼、初始密碼和其他數(shù)據(jù)(對(duì)實(shí)際數(shù)據(jù)庫(kù)的簡(jiǎn)化模擬);
第2行:定義函數(shù);
第3行:使用input獲得用戶輸入的字符串并儲(chǔ)存在變量password中;
第4行:當(dāng)用戶輸入的密碼等于密碼列表中最后一個(gè)元素的時(shí)候(即用戶最新設(shè)定的密碼),登錄成功
第5-9行:當(dāng)用戶輸入的密碼等于密碼列表中第一個(gè)元素的時(shí)候(即重置密碼的“口令”)觸發(fā)密碼變量,并將變更后的密碼儲(chǔ)存至列表的最后一個(gè),成為最新的用戶密碼;
第10行:反之,一切不等于預(yù)設(shè)密碼的輸入結(jié)果,全部會(huì)執(zhí)行打印錯(cuò)誤提示,并且再次調(diào)用函數(shù),讓用戶再次輸入密碼;
第11行:調(diào)用函數(shù)。
for循環(huán)
>>> for every_letter in 'Hello world':
print(every_letter)
H
e
l
l
o
w
o
r
l
d
- 說(shuō)明
加深理解
>>> for num in range(1,11):
print(str(num) + ' + 1=',num + 1)
1 + 1= 2
2 + 1= 3
3 + 1= 4
4 + 1= 5
5 + 1= 6
6 + 1= 7
7 + 1= 8
8 + 1= 9
9 + 1= 10
10 + 1= 11
while循環(huán)
控制while循環(huán),在循環(huán)過程中制造某種可以使循環(huán)停下來(lái)的條件
>>> while True:
print('Repeat this line !')
count = count + 1
if count == 5:
break
Repeat this line !
Repeat this line !
Repeat this line !
Repeat this line !
Repeat this line !
除此之外,讓 While 循環(huán)停下來(lái)的另一種方法是:改變使循環(huán)成立的條件。為了解釋這個(gè)例子,我們?cè)谇懊娴卿浐瘮?shù)的基礎(chǔ)上來(lái)實(shí)現(xiàn),給登錄函數(shù)增加一個(gè)新功能:輸入密碼錯(cuò)誤超過3次就禁止再次輸入密碼
password_list = ['*#*#','12345']
def account_login():
tries = 3
while tries > 0:
password = input('Password:')
password_correct = password == password_list[-1]
password_reset = password == password_list[0]
if password_correct:
print('Login success!')
elif password_reset:
new_password = input('Enter a new password:')
password_list.append(new_password)
print('Your password has changed successfully!')
account_login()
else:
print('Wrong password or invalid input!')
tries = tries -1
print( tries, 'times left')
else:
print('Your account has been suspended')
account_login()
這段代碼只有三處與前面的不一樣:
第4-5行:增加了 while 循環(huán),如果 tries > 0 這個(gè)條件成立,那么便可輸入密碼,從而執(zhí)行辨別密碼是否正解的邏輯判斷;
第20-21行:當(dāng)密碼輸入錯(cuò)誤時(shí),可嘗試的次數(shù) tries 減少1;
第23-24行:while 循環(huán)的條件不成立時(shí),就意味著嘗試次數(shù)用光,通告用戶賬戶被鎖。在這里while可以理解成是 if 循環(huán)版,可以使用 while-else結(jié)構(gòu),而在 while 代碼塊中又存在著第二層的邏輯判斷,這其實(shí)構(gòu)成了嵌套邏輯(NestedCondition)
練習(xí)題 P70
1、設(shè)計(jì)這樣一個(gè)函數(shù),在桌面的文件夾上創(chuàng)建10個(gè)文本,以數(shù)字給它們命名。
def text_creation():
path = 'D:\\'
for name in range (1,11):
with open(path + str(name) + '.txt','w') as text:
text.write(str(name))
text.close()
print('Done')
text_creation()
2、復(fù)利是一件神奇的事情,正如富蘭克林所說(shuō):“復(fù)利是能夠?qū)⑺秀U塊變成金塊的石頭”。設(shè)計(jì)一個(gè)復(fù)利計(jì)算 invest(),它包含三個(gè)參數(shù): amount (資金), rate (利率),time (投資時(shí)間)。輸入每個(gè)參數(shù)后調(diào)用函數(shù),應(yīng)該返回每一年的資金總額。它看起來(lái)就應(yīng)該像這樣 (假設(shè)利率為5%):
def invest(amount, rate, time):
print("principal amount:{}".format(amount))
for t in range(1, time + 1):
amount = amount * (1 + rate)
print("year {}: ${}".format(t, amount))
invest(100, .05, 8)
invest(2000, .025, 5)
3、打印1-100內(nèi)的偶數(shù)
不能整除的數(shù)就是偶數(shù)
def even_print():
for i in range(1,101):
if i % 2 == 0:
print(i)
even_print()
import random
def roll_dice(number=3, points=None):
print('<<<<< ROLL THE DICE! >>>>>')
if points is None:
points = []
while numbers > 0:
point = random.randrange(1,7)
points.append(point)
numbers = numbers - 1
return points
def roll_result(total):
isBig = 11 <= total <= 18
isSmaill = 3 <= total <=10
if isBig:
return 'Big'
elif isSmaill:
return 'Small'
def start_game():
print('<<<<< GAME STARTS! >>>>>')
choices = ['Big','Small']
your_choice = input('Big or Small :')
if your_choice in choices:
points = roll_dice()
total = sum(points)
youWin = your_choice == roll_result(total)
if youWin:
print('The points are',points,'You win !')
else:
print('The points are',points,'You lose !')
else:
print('Invalid Words')
start_game()
start_game()