Python - 为什么我的else语句在这段代码中被忽略了?

时间:2015-06-08 18:19:43

标签: python if-statement python-3.1

seats = 3
rating = 12

print('Hello and welcome to Daisy\'s cinema.')

while seats > 0:
    name = input('What is your name?')
    print('Hello',name,'\n')
    print('We are currently showing Mockingjay at out cinema.')
    film = input('What film would you like to watch?')
    if film != 'Mockingjay' or 'mockingjay':
        print('I\'m sorry but we aren\'t showing that film.\n\n')
    else:
        print('This film currently has',seats,'free seats and a certificate of',rating,'\n')
        age = int(input('How old are you?'))
        if age > 15 or age == 15:
            print('You have booked a ticket to see this film.\n\n')
            seats == seats-1
        else:
            print('I\'m sorry but you\'re too young to see this film.\n\n')

print('Mockingjay is now full. Thank you for booking your tickets. \n\n')

这段代码根本不起作用。当我把Mockingjay或者mockingjay之外的其他东西放到电影片头上时,它的效果很好,但是如果我把它们放在里面仍然说这部电影没有显示出来。什么时候应该继续说明有多少个免费座位以及证书是什么。有任何想法吗?我使用Python 3.1。

1 个答案:

答案 0 :(得分:4)

if film != 'Mockingjay' or 'mockingjay':

需要

if film.upper() != 'MOCKINGJAY':

原因是or 'mockingjay'总是True。 (bool('mockingjay') = True

使用film.upper()有助于确保无论输入情况如何:mocKinjayMOCKINgjaymockingjay等,它始终会捕获。

如果要检查2个不同的字符串,请使用:

if film not in ['Mockingjay', 'mockingjay']:
if film != 'mockingjay' and film != 'Mockingjay':

注意and,如果我们在此处使用or并传入Mockingjay,则该语句仍会评估,因为film != 'mockingjay'