基于列表创建基于菜单的程序

我在创建一个菜单驱动的程序时遇到了问题,该程序应该接受整数,并计算平均值和中位数并显示它们。我在计算平均数或中位数时没有问题,但在将列表配置到程序中时遇到了问题。

选择 | 换行 | 行号
  1. #Main
  2. def main():
  3.     array = [] #this would be the list, but what do i do with it?
  4.     choice = displayMenu()
  5.     while choice != '4':
  6.         if choice == '1':
  7.             addNum()
  8.         if choice == '2':
  9.             calcMean()
  10.         if choice == '3':
  11.             displayMedian()
  12.         choice = displayMenu()
  13.  

现在,这是我的主要功能。我不完全确定该怎么处理这份清单。下一部分是displayMenu()函数,但这是正确的,所以我不打算发布它。然而,接下来是选项1,即addNum()函数。

选择 | 换行 | 行号
  1. #adding numbers to the list
  2. def addNum(): #how do I get it to return to the list in main?
  3.     number = raw_input("Enter number: ")
  4.     array.append(number)
  5.  

我感觉我就快把这件事做对了,但与此同时,我完全被困住了,不知道该怎么办。
任何帮助、建议和意见都将不胜感激。谢谢

# 回答1


我不知道这是什么意思,但一般来说,您没有从该函数返回任何内容。你必须从函数中返回一个变量,因为在函数中所做的任何更改都会留在函数中,以改变维加斯短语,除非你将值返回给函数外的某个变量。这是非常基本的东西,您应该知道,所以不要自己编写代码,而是从一本在线书籍开始
这里

这里。

选择 | 换行 | 行号
  1. ##   see the Python style guide http://www.python.org/dev/peps/pep-0008/
  2. ##   function and variable names are all lower case
  3. def add_num(array): #how do I get it to return to the list in main?
  4.     number = raw_input("Enter number: ")
  5.     array.append(number)
  6.     return array
  7.  
  8. ##   calling main() from "if __name__ == '__main__' is redundant (unnecessary)
  9. ##   and considered bad style as it is not obvious that this code runs when you
  10. ##   run this program (as opposed to executing a function from another program).
  11. if __name__ == '__main__:
  12.     array = [] #this would be the list, but what do i do with it?
  13.     choice = displayMenu()
  14.     while choice != '4':
  15.         if choice == '1':
  16.             array = add_num(array)
  17.             print array
  18.         if choice == '2':
  19.             calcMean()
  20.         if choice == '3':
  21.             displayMedian()
  22.         choice = displayMenu() 
# 回答2


非常感谢。我想我只是因为压力太大而错过了一些简单的东西。

标签: python

添加新评论