python if - elif-else用法和澄清

时间:2013-01-05 15:12:17

标签: python

"""
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子句。现在抛出语法错误。我做错了什么?

4 个答案:

答案 0 :(得分:3)

关于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':
    ...

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

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

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

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

您可能需要以下内容:

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

可以写成

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

答案 3 :(得分:0)

正如翻译所说,这是一个IndentationError。第31行的if语句缩进4个空格,而相应的else语句缩进5个空格。