0
"""
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

4 回答 4

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':
    ...
于 2013-01-05T15:14:29.373 回答
2

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

if choice.lower() == 'x':
于 2013-01-05T15:42:19.297 回答
0
if choice == 'x' or 'X':

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

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

您可能需要以下内容:

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

可以写成

if choice in ('x', 'X'):
于 2013-01-05T15:14:22.430 回答
0

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

于 2013-01-05T15:18:52.583 回答