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

Python - Why is my else statement being ignored in this piece of code?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
seats = 3
rating = 12

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

while seats > 0:
    name = input('What is your name?')
    print('Hello',name,'
'
)
    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.

'
)
    else:
        print('This film currently has',seats,'free seats and a certificate of',rating,'
'
)
        age = int(input('How old are you?'))
        if age > 15 or age == 15:
            print('You have booked a ticket to see this film.

'
)
            seats == seats-1
        else:
            print('I\'m sorry but you\'re too young to see this film.

'
)

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

'
)

这段代码根本不起作用。当我为电影的片名加上嘲弄杰伊或嘲弄杰伊以外的东西时,效果很好,但如果我把它们放进去,它仍然会说这部电影没有上映。什么时候应该继续说有多少个空座位,以及证书是什么。有什么想法吗?我使用python 3.1。


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

需要

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

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

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

如果要对照两个不同的字符串进行检查,请使用以下任一项:

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

注意到and,如果我们在这里使用or并传入MOCKINgjay,该语句仍将进行评估,因为film != 'mockingjay'