【问题标题】:python if--elif-else usage and clarificationpython if--elif-else用法及说明
【发布时间】:2013-01-05 15:12:17
【问题描述】:
"""
This program presents a menu to the user and based upon the selection made
invokes already existing programs respectively.
"""
import sys

def get_numbers():
  """get the upper limit of numbers the user wishes to input"""
  limit = int(raw_input('Enter the upper limit: '))
  numbers = []

  # obtain the numbers from user and add them to list
  counter = 1
  while counter <= limit:
    numbers.append(int(raw_input('Enter number %d: ' % (counter))))
    counter += 1

  return numbers

def main():
  continue_loop = True
  while continue_loop:
    # display a menu for the user to choose
    print('1.Sum of numbers')
    print('2.Get average of numbers')
    print('X-quit')

    choice = raw_input('Choose between the following options:')

    # if choice made is to quit the application then do the same
    if choice == 'x' or 'X':
      continue_loop = False
      sys.exit(0)

    """elif choice == '1':  
         # invoke module to perform 'sum' and display it
         numbers = get_numbers()
         continue_loop = False
         print 'Ready to perform sum!'

       elif choice == '2':  
         # invoke module to perform 'average' and display it
         numbers = get_numbers()
         continue_loop = False
         print 'Ready to perform average!'"""

     else:
       continue_loop = False    
       print 'Invalid choice!'  

if __name__ == '__main__':
  main()

只有当我输入“x”或“X”作为输入时,我的程序才会处理。对于其他输入,程序将退出。我已经注释掉了 elif 部分,并且只使用了 if 和 else 子句。现在抛出语法错误。我做错了什么?

【问题讨论】:

  • 您的语法错误来自else: 行缩进了一个空格。

标签: python


【解决方案1】:

关于if choice == 'x' or 'X'这一行。

没错,应该是

if choice == 'x' or choice == 'X'

或更简单的

if choice in ('X', 'x')

因为 or 运算符在两边都需要布尔表达式。

目前的解决方案解释如下:

if (choice == 'x') or ('X')

您可以清楚地看到'X' 没有返回布尔值。

另一种解决方案当然是检查大写字母是否等于“X”或小写字母是否等于“x”,可能如下所示:

if choice.lower() == 'x':
    ...

【讨论】:

  • 'X' 可以在 if 语句中使用 - 但由于它是一个非空字符串,它将评估为 True 并导致语句 if choice =='x' or 'X' 始终为 True
  • 很好的观察,当然你是对的,但我只是简化了它以向他表明在这种情况下评估非空字符串是没有意义的。
  • 永远不知道或期望两边都是布尔值。感谢您更清楚地解释它以及更pythonic。
  • 没问题。正如@DanielB 之前解释的那样,“或”并不严格期望双方都有布尔值,例如非空字符串也评估为“真”。我只是想表明在这种情况下这在语义上是错误的。
【解决方案2】:

您的问题在于您的 if choice == 'x' or 'X': 部分。要解决此问题,请将其更改为:

if choice.lower() == 'x':

【讨论】:

    【解决方案3】:
    if choice == 'x' or 'X':
    

    没有做你认为它正在做的事情。实际得到的解析如下:

    if (choice == 'x') or ('X'):
    

    您可能想要以下内容:

    if choice == 'x' or choice == 'X':
    

    可以写成

    if choice in ('x', 'X'):
    

    【讨论】:

    • 可以写成好像在('x', 'X')中选择
    • 或者在这种情况下,更简单的if choice.lower() == 'x':
    • @bgporter。这是编写表达式的更独立于语言的选择。非常感谢您的提醒。
    【解决方案4】:

    正如解释器所说,这是一个 IndentationError。第 31 行的 if 语句缩进 4 个空格,而对应的 else 语句缩进 5 个空格。

    【讨论】:

    • 谢谢,因为我在提问时复制了代码并粘贴了,所以我不得不打算使用它们,并且错误地我会添加一个额外的空间
    猜你喜欢
    • 1970-01-01
    • 2017-05-03
    • 2017-07-03
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多