Python的概念。其他声明打印时不应该

时间:2015-03-08 23:51:48

标签: python if-statement logic

这是一个初学程序员的概念问题。我还在研究这个项目。当我输入一个菜单选项时,不仅会打印相应的if语句,而且else语句也可以。有了这个python知识我就不明白为什么了。我想知道是什么触发了我的其他声明。

    FIND_LOWEST_NUMBER_CHOICE = 1
    FIND_HIGHEST_NUMBER_CHOICE = 2
    FIND_TOTAL_CHOICE = 3
    FIND_AVERAGE_CHOICE = 4
    QUIT_CHOICE = 5

    def main():
        numbers = get_values()
        get_analysis(numbers)
    def get_values():
        print('Please enter 20 numbers')
        values =[]    
        for i in range(20):
            value =(int(input("Enter A Random Number " + str(i + 1) + ": ")))
            values.append(value)
        return values
    def get_analysis (numbers):
        choice = 0
        while choice != QUIT_CHOICE:
            display_menu()
            choice = int(input('Enter your choice:'))
            if choice == FIND_LOWEST_NUMBER_CHOICE:
                print("The Lowest Number Is:",  min(numbers))
            if choice == FIND_HIGHEST_NUMBER_CHOICE:
                print("The Highest Number Is:", max(numbers))
            if choice == FIND_TOTAL_CHOICE:
                print("The Sum The Numbers Is:", sum(numbers))
            if choice == FIND_AVERAGE_CHOICE:
                print("The Average The Numbers Is:", sum(numbers)/len(numbers))
            if choice == QUIT_CHOICE:
                print("Exiting program....")
            else:
                print('Error')

    def display_menu():
        print(' Menu')
        print('1. Show lowest number')
        print('2. Show highest number')
        print('3. Show total of numbers')
        print('4. Show average of numbers')
        print('5. Quit')

    main()

谢谢!

1 个答案:

答案 0 :(得分:0)

你应该使用elif,因为在你的代码中,else只匹配最后一个if。

例如:

if choice == FIND_LOWEST_NUMBER_CHOICE:
    print("The Lowest Number Is:",  min(numbers))
elif choice == FIND_HIGHEST_NUMBER_CHOICE:
    print("The Highest Number Is:", max(numbers))
elif choice == FIND_TOTAL_CHOICE:
    print("The Sum The Numbers Is:", sum(numbers))
elif choice == FIND_AVERAGE_CHOICE:
    print("The Average The Numbers Is:", sum(numbers)/len(numbers))
elif choice == QUIT_CHOICE:
    print("Exiting program....")
else:
    print('Error')