2014-09-28 85 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中以其他方式。

相关问题