菜单驱动的非负整数集合

时间:2017-03-13 16:08:26

标签: python

我试图创建一个菜单驱动的程序,其中python将接受一组非负整数。它将计算平均值和中位数并在屏幕上显示值。我希望我的第一个选项是"在列表/数组中添加一个数字",我希望我的第二个选项是"显示平均值",第三个选项是"显示中位数",第四个"将列表/数组打印到屏幕",第五个"以相反顺序打印列表/数组"最后一个选项" Quit"。到目前为止,我已经得到了:

def main():
    myList = [ ]
    addOne(myList)
    choice = displayMenu()
    while choice != '6':
        if choice == '1':
            addOne(myList)
        elif choice == '2':
            mean(myList)
        elif choice == '3':
            median(myList)
        elif choice == '4':
             print(myList)
        elif choice == '5':
            print(myList)
        choice = displayMenu()


    print ("\nThanks for playing!\n\n")

def displayMenu():
    myChoice = '0'
    while myChoice != '1' and myChoice != '2' \
              and myChoice != '3' \
              and myChoice != '4' and myChoice != '5':
        print("""\n\nPlease choose
                1. Add a number to the list/array
                2. Display the mean
                3. Display the median
                4. Print the list/array to the screen
                5. Print the list/array in reverse order
                6. Quit
                """)
        myChoice = input("Enter option---> ")
        if myChoice != '1' and myChoice != '2' and \
           myChoice != '3' and myChoice != '4' and myChoice != '5':
            print("Invalid option. Please select again.")

    return myChoice

#This should make sure that the user puts in a correct input
def getNum():
    num = -1
    while num < 0:
        num = int(input("\n\nEnter a non-negative integer: "))
        if num < 0:
            print("Invalid value. Please re-enter.")

    return num

#This is to take care of number one on the list: Add number
def addOne(myList):
    while True:
        try:
            num = (int(input("Give me a number:")))
            num = int(num)
            if num < 0:
                raise exception
            print("Thank you!")
            break
        except:
            print("Invalid. Try again...")
        myList.append(num)


#This should take care of the second on the list: Mean
def mean(myList):
    myList = [ ]
    listSum = sum(myList)
    listLength = len(myList)
    listMean = listSum / listLength
    print("The mean is", listMean)

#This will take care of number three on the list: Median
def median(myList):
    median = 0
    sortedlist = sorted(myList)
    lengthofthelist = len(sortedlist)
    centerofthelist = lengthofthelist / 2
    if len(sortedlist) % 2 ==0:
        return sum(num[center - 1:center + 1]) / 2.0
    else:
        return num[center]
    print("The mean is", centerofthelist)


#This will take care of the fourth thing on the list: Print the list (In order)
def sort(myList):
    theList.sort(mylist)
    print(myList) 

#This will take care of the fifth thing on the list
def reversesort(myList):
    theList.sort(reverse=True)
    print(myList)


main() 

运行程序后,我无法创建列表。

2 个答案:

答案 0 :(得分:1)

更正了最小变化的代码:

def main():
    myList = []
    choice = 1
    while choice != 6:
        if choice == 1:
            option1(myList)
        elif choice == 2:
            option2(myList)
        elif choice == 3:
            option3(myList)
        elif choice == 4:
            option4(myList)
        elif choice == 5:
            option5(myList)
        choice = displayMenu()


    print ("\nThanks for playing!\n\n")

def displayMenu():
    myChoice = 0
    while myChoice not in [1, 2, 3, 4, 5]:
        print("""\n\nPlease choose
                1. Add a number to the list/array
                2. Display the mean
                3. Display the median
                4. Print the list/array
                5. Print the list/array in reverse order
                6. Quit
                """)
        myChoice = int(input("Enter option---> "))
        if myChoice not in [1, 2, 3, 4, 5]:
            print("Invalid option. Please select again.")

    return myChoice

# Option 1: Add a number to the list/array
def option1(myList):
    num = -1
    while num < 0:
        num = int(input("\n\nEnter a non-negative integer: "))
        if num < 0:
            print("Invalid value. Please re-enter.")
    myList.append(num)


# Option 2: Display the mean
def option2(myList):
    print("The mean is ", sum(myList) / len(myList))

# Option 3: Display the median
def option3(myList):
    sortedlist = sorted(myList)
    if len(sortedlist) % 2:
        median = myList[int(len(sortedlist) / 2)]
    else:
        center = int(len(sortedlist) / 2)
        median = sum(myList[center-1:center+1]) / 2
    print("The median is", median)


# Option 4: Print the list/array
def option4(myList):
    print(sorted(myList))

# Option 5: Print the list/array in reverse order
def option5(myList):
    print(sorted(myList, reverse=True))


main()

我将如何做到这一点:

以下代码的第一部分是一组用于自定义菜单样式的常量。然后定义表示每个选项的一组函数。以下3个功能应该进行修改,它们会生成菜单,显示它并关闭应用程序。然后主要部分开始,您需要将每个选项作为参数传递给setOptions()。其余的应该,因为它是主循环。

# Menu formatting constants
MENU_HEADER = "Please choose an option:"
MENU_FORMAT = " * {:2}. {}"
MENU_QUIT_S = "Quit"
MENU_ASK_IN = "Enter option: "
MENU_INT_ER = "ERROR: Invalid integer. Please select again."
MENU_OPT_ER = "ERROR: Invalid option. Please select again."
END_MESSAGE = "Thanks for playing!"

# OPTIONS FUNCTIONS START HERE

def addElement(l):
    """ Add a number to the list/array. """
    n = -1
    while n < 0:
        try:
            n = int(input("Enter a non-negative integer: "))
        except ValueError:
            print("It needs to be an integer.")
            n = -1
        else:
            if n < 0:
                print("It needs to be a non-negative integer.")
    l.append(n)


def mean(l):
    """ Calculate the mean. """
    print("Mean: {:7.2}".format(sum(l) / len(l)))


def median(l):
    """ Calculate the median. """
    l = sorted(l)
    p = int(len(l) / 2)
    print("Median: {:7.2}".format(l[p] if len(l)%2 else sum(l[p-1:p+1])/2))


def oprint(l):
    """ Print the list/array. """
    print(sorted(l))


def rprint(l):
    """ Print the list/array in reverse order. """
    print(sorted(l, reverse=True))

# OPTIONS FUNCTIONS END HERE

def onQuit(l):
    """ Function to execute when quitting the application. """
    global quit
    quit = True
    print(END_MESSAGE)


def setOptions(*args):
    """ Generates the menu and the options list. """
    # Menu header and quit option (option 0)
    menu = [MENU_HEADER]
    options = [onQuit]
    # Passed arguments represent texts and functions of additional options
    for i, f in enumerate(args, start=1):
        menu.append(MENU_FORMAT.format(i, f.__doc__.strip()))
        options.append(f)
    # We print the option 0 the last one
    menu.append(MENU_FORMAT.format(0, MENU_QUIT_S))
    # Returning both the menu and the options lists
    return tuple(menu), tuple(options)


def displayMenu(menu):
    """ Display the menu and get an option that is an int. """
    while True:
        for line in menu:
            print(line)
        try:
            choice = int(input(MENU_ASK_IN))
        except ValueError:
            print(MENU_INT_ER)
        else:
            return choice

if __name__ == '__main__':
    # Pass the option functions to the setOptions function as arguments
    menu, options = setOptions(
        addElement,
        mean,
        median,
        oprint,
        rprint
    )
    # Initiate the needed variables and start the loop
    l = []
    quit = False
    while not quit:
       c = displayMenu(menu)
       try:
           f = options[c]
       except IndexError:
           print(MENU_OPT_ER)
       else:
           f(l)

答案 1 :(得分:0)

您的函数addOne中存在缩进错误。

myList.append(num)在while循环中,就在此之前你有一个break,所以这个数字永远不会附加到列表中,因为我们已经离开了循环。