我在创建一个菜单驱动的程序时遇到了问题,该程序应该接受整数,并计算平均值和中位数并显示它们。我在计算平均数或中位数时没有问题,但在将列表配置到程序中时遇到了问题。
- #Main
- def main():
- array = [] #this would be the list, but what do i do with it?
- choice = displayMenu()
- while choice != '4':
- if choice == '1':
- addNum()
- if choice == '2':
- calcMean()
- if choice == '3':
- displayMedian()
- choice = displayMenu()
-
现在,这是我的主要功能。我不完全确定该怎么处理这份清单。下一部分是displayMenu()函数,但这是正确的,所以我不打算发布它。然而,接下来是选项1,即addNum()函数。
- #adding numbers to the list
- def addNum(): #how do I get it to return to the list in main?
- number = raw_input("Enter number: ")
- array.append(number)
-
我感觉我就快把这件事做对了,但与此同时,我完全被困住了,不知道该怎么办。
任何帮助、建议和意见都将不胜感激。谢谢
# 回答1
我不知道这是什么意思,但一般来说,您没有从该函数返回任何内容。你必须从函数中返回一个变量,因为在函数中所做的任何更改都会留在函数中,以改变维加斯短语,除非你将值返回给函数外的某个变量。这是非常基本的东西,您应该知道,所以不要自己编写代码,而是从一本在线书籍开始
这里
或
这里。
- ## see the Python style guide http://www.python.org/dev/peps/pep-0008/
- ## function and variable names are all lower case
- def add_num(array): #how do I get it to return to the list in main?
- number = raw_input("Enter number: ")
- array.append(number)
- return array
-
- ## calling main() from "if __name__ == '__main__' is redundant (unnecessary)
- ## and considered bad style as it is not obvious that this code runs when you
- ## run this program (as opposed to executing a function from another program).
- if __name__ == '__main__:
- array = [] #this would be the list, but what do i do with it?
- choice = displayMenu()
- while choice != '4':
- if choice == '1':
- array = add_num(array)
- print array
- if choice == '2':
- calcMean()
- if choice == '3':
- displayMedian()
- choice = displayMenu()
# 回答2
非常感谢。我想我只是因为压力太大而错过了一些简单的东西。