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

インタプリタが言うように、それは IndentationError です。31 行目の if ステートメントは 4 つのスペースでインデントされていますが、対応する else ステートメントは 5 つのスペースでインデントされています。

于 2013-01-05T15:18:52.583 に答える
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 に答える