首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >菜单驱动的非负整数集合

菜单驱动的非负整数集合
EN

Stack Overflow用户
提问于 2017-03-13 16:08:25
回答 2查看 446关注 0票数 0

我正在尝试创建一个菜单驱动的程序,python将接受非负整数的集合。它将计算平均值和中值,并在屏幕上显示这些值。我希望我的第一个选项是“向列表/数组添加一个数字”,我希望我的第二个选项是“显示平均值”,第三个选项是“显示中值”,第四个选项是“打印列表/数组到屏幕”,第五个选项是“以反向顺序打印列表/数组”和最后一个选项“退出”。到目前为止我得到了:

代码语言:javascript
复制
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() 

在我运行程序之后,我无法通过创建列表。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-13 16:35:06

修正后的代码,并有最小的更改:

代码语言:javascript
复制
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()。其余的应该修改,而不是,因为它是主循环。

代码语言:javascript
复制
# 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
EN

Stack Overflow用户

发布于 2017-03-13 16:35:41

函数addOne中存在缩进错误。

myList.append(num)在while循环中,就在此之前,您有一个break,因此这个数字从未追加到列表中,因为我们已经离开了循环。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42768303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档