2014-03-28 77 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()