2014-03-28 76 views
0

之前停止Python中退出程序的方法我使用以下代碼構建了一個簡單的Python程序,該程序從用戶獲取輸入。如果執行命令

Name = raw_input('Enter your name: ') 
Age = raw_input('Enter you age:') 
Qualifications = raw_input('Enter you Qualification(s):') 
A = raw_input() 

print "Hello" +'.'+ "Your Name is " + Name + ". " + "Your Age is " + Age + ". " + "Your Qualification(s) is/are:" + Qualifications + "." 
print "If the above data is correct, type yes. If not, type no. Typing no will restart he program and make you write the form again." + A 
if A in ['y', 'Y', 'yes', 'Yes', 'YES']: 
    print 'Thanks for your submission' 
if A in ['No' , 'no' , 'NO' ,'n' , 'N']: 
    reload() 

程序在if命令之前完成。

+0

代碼在「if」命令之前絕對沒有理由 – sshashank124

+2

您是否認爲如果'A'只是Yes或No的變體之一,您的程序將會完成? – msvalkon

+2

您可能需要將'A = raw_input()'移動到以'print'開頭的兩行之下。目前用戶必須在看到指令之前進行確認 – Gryphius

回答

2

如果你給什麼,但['y', 'Y', 'yes', 'Yes', 'YES']['No' , 'no' , 'NO' ,'n' , 'N'],你的程序將完成,並在各自if -clauses不執行任何語句。

reload()函數不會做你期望的。它用於重新加載模塊,應該在解釋器中使用。它還需要先前導入module作爲它的參數,在沒有調用它的情況下會提高TypeError

因此,爲了實際再次提出問題,您需要一個循環。例如:

while True: 
    name = raw_input('Enter your name: ') 
    age = raw_input('Enter your age: ') 
    qualifications = raw_input('Enter your Qualification(s): ') 

    print "Hello. Your name is {}. Your age is {}. Your qualifications are: {}".format(name, age, qualifications) 
    quit = raw_input("Is the above data correct [yY]? ").lower() # notice the lower() 
    if quit in ("y", "yes"): 
     break 
    else: 
     # If the input was anything but y, yes or any variation of those. 
     # for example no, foo, bar, asdf.. 
     print "Rewrite the form below" 

如果你現在輸入任何東西比y, Yyes任何變化,該方案將再次提出的問題。

+0

如果用戶輸入除yes或no以外的其他內容,我希望程序再次詢問輸入。如果用戶輸入「否」,則在再次提出問題之前,程序必須打印「重寫下面的表格」。 –

+0

@VishalSubramanyam這是程序的功能,直到無限。我更新了包含該印刷品的答案。如果你真的想檢查'no'的情況,只需添加一個類似的檢查,如'是'的情況。 – msvalkon

0

移動你的A raw_input行後打印「你的名字是...」和東西。像這樣:

我還讓腳本一直詢問重新啓動,直到輸入有效。

Name = raw_input('Enter your name: ') 
Age = raw_input('Enter you age:') 
Qualifications = raw_input('Enter you Qualification(s):') 

print "Hello" +'.'+ "Your Name is " + Name + ". " + "Your Age is " + Age + ". " + "Your Qualification(s) is/are:" + Qualifications + "." 
print "If the above data is correct, type yes. If not, type no. Typing no will restart he program and make you write the form again." 

yes = ['y', 'Y', 'yes', 'Yes', 'YES'] 
no = ['No' , 'no' , 'NO' ,'n' , 'N'] 

A = '' 

while A not in (yes+no): # keep asking until the answer is a valid yes/no 
    A = raw_input("Again?: ") 

if A in yes: 
    print 'Thanks for your submission' 
if A in no: 
    reload()