即使输入错误,elif语句也会一直执行

时间:2012-04-27 13:52:24

标签: python if-statement

我在elif语句中选择Y和N时遇到问题。 如果我输入n它正确输出n的elif选项,但是如果我输入y它仍然输出n选项而不是elif选项y。我不知道它为什么这样做。对于代码感到抱歉,如果错误明白,我是python的新手 我检查了选择,它确实保留了n或y的选择,但即使y输入也只执行n。

if os.path.exists('ExifOutput.txt'): 
                    print "The file appears to already exist, would you like to overwrite it?" 
                    Choice = raw_input("Y/N : ") 
                    if not re.match("^[Y,y,N,n]*$", Choice): 
                        print "Error! Only Choice Y or N allowed!" 
                    elif len(Choice) > 1: 
                        print "Error! Only 1 character allowed!" 
                    elif not Choice:
                        print "No choice made" 
                    elif Choice == 'N' or 'n': 
                        print "Save the old file to a different directory and try again"
                        ExifTags()
                    elif Choice == 'Y' or 'y':
                        print "The file will be overwritten by a new one"
                        ExifRetrieval(listing, FileLocation)
                        print "Completed" + "\n"
                else:
                    ExifRetrieval(listing, FileLocation)
                    print "Completed" + "\n"

2 个答案:

答案 0 :(得分:4)

Choice == 'N' or 'n'始终为真(与(Choice == 'N') or 'n'相同)。你想要Choice in ('N', 'n')

答案 1 :(得分:0)

elif Choice == 'N' or Choice == 'n':

elif Choice in ("N","n"):