即使输入错误,elif语句也总是执行

2024-04-23 11:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我对elif语句中的Y和N选项有问题。 如果我输入n,它正确地输出了n的elif选项,但是如果我输入y,它仍然输出n选项而不是elif选项y。我不知道它为什么这样做。很抱歉,如果代码中的错误一目了然,我是python新手。
我已经检查了choice,它确实保留了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"

Tags: orthetoonlyif选项noterror
2条回答

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

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

或者

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

相关问题 更多 >