2013-12-09 22 views
1
password = str() 

while password != "changeme": 
    password = input("Password: ") 
print("Thou Shall Pass Into Mordor") 
else print("Thou Shall Not Pass Into Mordor") 

我可以請我的代碼有一些helo。需要幫助把其他的東西放入計數器的同時

我想讓它在密碼不正確5次的情況下打印「雖然不會進入Mordor」。有人可以幫幫我嗎!有人也可以請一個櫃檯嗎?

回答

4

使用break結束一個循環,並使用forrange()

for attempt in range(5): 
    password = input("Password: ") 
    if password == "changeme": 
     print("Thou Shall Pass Into Mordor") 
     break 
else: 
    print("Thou Shall Not Pass Into Mordor") 

一個for循環的else分支當你沒有使用break結束僅環執行。

演示:

>>> # Five failed attempts 
... 
>>> for attempt in range(5): 
...  password = input("Password: ") 
...  if password == "changeme": 
...   print("Thou Shall Pass Into Mordor") 
...   break 
... else: 
...  print("Thou Shall Not Pass Into Mordor") 
... 
Password: You shall not pass! 
Password: One doesn't simply walk into Mordor! 
Password: That sword was broken! 
Password: It has been remade! 
Password: <whispered> Toss me! 
Thou Shall Not Pass Into Mordor 
>>> # Successful attempt after one failure 
... 
>>> for attempt in range(5): 
...  password = input("Password: ") 
...  if password == "changeme": 
...   print("Thou Shall Pass Into Mordor") 
...   break 
... else: 
...  print("Thou Shall Not Pass Into Mordor") 
... 
Password: They come in pints?! I'm having one! 
Password: changeme 
Thou Shall Pass Into Mordor 
+0

你應該改變'input'到'raw_input'。 'input'將嘗試評估輸入是什麼,但raw_input將簡單地將其作爲一個字符串。在這種情況下,你想'raw_input'。 –

+0

@KyleNeary OP是使用python 3. – roippi

+0

@KyleNeary:我已經在你現在刪除的答案中評論了這個。 'raw_input'在Python 3中沒有了,它已經被重命名爲'input()',並且來自Python 2的舊'input()'不見了。 –

相關問題