【问题标题】:Python - Why is my else statement being ignored in this piece of code? [duplicate]Python - 为什么我的 else 语句在这段代码中被忽略了? [复制]
【发布时间】:2015-06-08 18:19:43
【问题描述】:
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。

【问题讨论】:

  • @ZdaR,该表达式的计算结果始终为 true。

标签: python if-statement python-3.1


【解决方案1】:
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'

【讨论】:

  • 可能值得补充一下为什么它总是正确的
  • 这是正确的,从没想过,但感谢您的帮助!
猜你喜欢
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多