2014-09-28 87 views
0

您好我是一個新的Python 2.7.3,我試圖編寫一個自動退出條款後兩個if語句。爲什麼我不能得到一個退出命令工作

import os 

password = "Anhur" 
attempt = 0 
while (password != "Anhur") and (attempt <= 3): 
    password = raw_input("Password: ") 
    attempt = attempt + 1 
    if attempt == 3: 
     print ("You have used all your attempts, the system will now close..") 
     print (" The shifting sands have ended you.") 
     break 

if (password == "Anhur"): 
    print ("You conquered the sands") 

os.exit(1) 

這是我得到的,但它似乎從來沒有工作我試圖sys.exit(0)以及。任何幫助將是美好的。

回答

1

只需使用exit()


import os 

password="" 
attempt=0 
while (password != "Anhur") and (attempt<3): 
    password=raw_input("Password: ") 
    attempt+=1 

    if (password == "Anhur"): 
     print ("You conquered the sands") 
     exit() 

print ('''You have used all your attempts, the system will now close..") 
The shifting sands have ended you.''') 
0

rsm, 有用的答案。但是最初的代碼是buggy和恕我直言沒用。請嘗試這一個:

import os 

password = "" 
attempts = 0 
found = False 
while (attempts <= 2): 
    password = raw_input("Password: ") 
    attempts = attempts + 1 
    if (password == "Anhur") : 
     found = True 
     break 

if found: 
    print ("You conquered the sands") 
    exit(0) 
else: 
    print ("You have used all of your attempts, the system will now close..") 
    print (" The shifting sands have ended you.") 
    exit(1) 

這允許在操作系統級別正確區分成功/失敗,例如,在csh/tcsh中的變量狀態(我工作時的默認shell)或者在其他更有用的/現代的shell中以其他方式。

相關問題