2016-07-18 39 views
-6

我只是想更好地理解python,所以我想我會使用 堆棧溢出作爲教程。 我一個完整的新手,所以忍耐一下,這是一個示例代碼,我想補充一個for語句或循環使代碼嘗試3次嘗試與 退出前「開溜」Python如何使用for循環

username = input('Login:>>') 

user1 = 'jack' 
user2 = 'jill' 

if username == user1: 
    print('access granted') 

elif username == user2: 
    print('welcome to the system') 

else: 
    print('access denied') 
+7

stackoverflow不是教程。請在發佈問題前進行調查。互聯網上有很多教程網站。請參閱http://meta.stackoverflow.com/q/261592/7432 –

回答

2
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') 
+0

感謝那和所有回答堆棧溢出作品的人 – alf

+0

'else'應該是縮進的。 – kindall

+0

不,我試過了,它工作。 –