为什么我不能让退出命令工作

时间:2014-09-28 03:32:13

标签: python-2.7

您好我是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)。任何帮助都会很精彩。

2 个答案:

答案 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.''')

答案 1 :(得分:0)

rsm, 有用的答案。然而,初始代码是错误的,恕我直言无用。请尝试这个:

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)

这允许在OS级别正确区分成功/失败,例如,在csh / tcsh中的变量状态(我工作时的默认shell)或更有用/现代shell中的其他方式。