如果命令,在停止程序退出Python之前该怎么做

时间:2014-03-28 06:35:48

标签: python if-statement user-input

我使用以下代码构建了一个从用户那里获得输入的简单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命令之前完成。

2 个答案:

答案 0 :(得分:2)

如果您提供['y', 'Y', 'yes', 'Yes', 'YES']['No' , 'no' , 'NO' ,'n' , 'N']以外的任何内容,您的计划将完成,而不会执行各自if - 条款中的任何陈述。

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的任何变体,程序将再次提出问题。

答案 1 :(得分: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()