2013-01-05 58 views
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子句。现在引发语法错误。我究竟做错了什么?python if - elif-else的用法和说明

+0

你的语法错误,从'其他地方发过来:'行正太一个空格缩进。 –

回答

3

这是关于线if choice == 'x' or 'X'

正确,应该是

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

或简单

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

因为或运营商期望双方布尔表达式。

目前的解决办法的解释如下:

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

,你可以清楚地看到,'X'不返回一个布尔值。

另一个解决方案是当然的,以检查是否如果大写字母等于“X”或小写字母等于“X”,这可能看起来像:

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

''X''可以在if语句中使用 - 但由于它是一个非空字符串,它将计算为'True'并导致语句'if choice =='x'或'X''始终为TRUE;。 – DanielB

+0

好的观察,当然你是对的,但我只是简化它,告诉他在这种情况下评估一个非空字符串是没有意义的。 – George

+0

永远不会知道或期望双方布尔值。感谢您更清楚地解释它以及pythonic。 – kunaguvarun

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

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

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

你可能想以下几点:

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

可以写成

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

可以写成('x','X') – Ant

+1

好点。这是更多Pythonic。 :) – johankj

+1

或在这种情况下,更简单的'如果choice.lower()=='x':' – bgporter

0

至于解释说,这是一个IndentationError。第31行的if语句缩进4个空格,而相应的else语句缩进5个空格。

+0

谢谢,因为我复制代码并粘贴问问题时,我不得不打算他们,我错了我会添加一个额外的空间 – kunaguvarun

2

你的问题是在你if choice == 'x' or 'X': part.To修复它改成这样:

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