user1 = 'jack'
user2 = 'jill'
for i in range(3):
username = input('Login:>>')
if username == user1:
print('access granted')
break
elif username == user2:
print('welcome to the system')
break
else:
print('access denied')
在這段代碼中,我們使用了一個for循環,它將運行3次。 但是,如果輸入的用戶名是真實的,程序退出循環與break
命令... 我們沒有把break
陳述在else
條件,使用戶可以嘗試用戶名3次。
編輯
@kindall我需要修改我的答案的評論... 當上面的代碼運行時,「拒絕訪問」顯示消息後,在屏幕上3次,但如果你想顯示它只有一次,你應該使用這個代碼:
user1 = 'jack'
user2 = 'jill'
access = 0
for i in range(3):
username = input('Login:>>')
if username == user1:
print('access granted')
access = 1
break
elif username == user2:
print('welcome to the system')
access = 1
break
if not access:
print('access denied')
stackoverflow不是教程。請在發佈問題前進行調查。互聯網上有很多教程網站。請參閱http://meta.stackoverflow.com/q/261592/7432 –