Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在全局列表中存储新号码,每次添加更多号码_Python_List_Global - Fatal编程技术网

Python 在全局列表中存储新号码,每次添加更多号码

Python 在全局列表中存储新号码,每次添加更多号码,python,list,global,Python,List,Global,我目前正试图让我的代码从用户那里收集一个号码,显示它,当输入一个新号码时,显示所有输入的号码。但每次我输入一个新的数字,它只会删除过去的数字,只显示输入的新数字。有什么帮助吗 def main(): def choiceTypeNumber(): global number number = input("Please type in a number -> ") print(&quo

我目前正试图让我的代码从用户那里收集一个号码,显示它,当输入一个新号码时,显示所有输入的号码。但每次我输入一个新的数字,它只会删除过去的数字,只显示输入的新数字。有什么帮助吗

def main():
    
    
    
    def choiceTypeNumber():
        global number
        number = input("Please type in a number -> ")
        print("Thank you for your number, now returning to menu.\n")
        menu()
        return number



    def choiceDisplayAll():
        global number
        print(number)
        menu()


    def choiceQuit():
        print("Goodbye!")
        exit()



    def menu():
        number = []
        menu = ["G] Get a number", "S] Display current sum", "A] Display current average",
                "H] Display the current highest numer", "L] Display the current lowest number",
                "D] Display all numbers entered", "Q] Quit"]


        print("##########################\n#Welcome to the program! # \n#Please input your choice#\n##########################\n")

        for item in menu:
            print(item)

        choice = input()

        if(choice.upper()== "G"):
            choiceTypeNumber()
            
        elif(choice.upper()== "D"):
            choiceDisplayAll()
        
        elif(choice.upper() == "Q"):
            choiceQuit()



    menu()

        
main()

添加到列表的方法是
.append
。当您说
number=input(“…”)
时,您正在将一个新值重新分配给
number
。如果过度使用,全局语句也会使代码变得混乱。如果列表位于其他函数之外,则可以在不使用全局语句的情况下对其进行变异

def main():
    numbers = []  # no need to use globals

    def choiceTypeNumber():
        numbers.append(input("Please type in a number -> "))  # You were overwriting the list here. Use append to add to the list
        print("Thank you for your number, now returning to menu.\n")
        menu()

    def choiceDisplayAll():
        for num in numbers:
            print(num, end=' ')  # print each number
        menu()

您可能还想检查G输入是否不是数字…忘记添加了。
import numpy as np

class SomeClassName():
    def __init__(self):
        self.numbers = []
        self.menu = ["G] Enter a new number", 
                     "S] Display current sum", 
                     "A] Display current average",
                     "H] Display the current highest numer", 
                     "L] Display the current lowest number",
                     "D] Display all numbers entered",
                     "M] Display the Menu"
                     "Q] Quit"]
    
        self.menuInputOptions = ['G', 'S', 'A', 'H', 'L', 'D', 'M', 'Q']
        self.quitFlag = True
        self.valid = False
        
        print ("##########################\n#Welcome to the program!\n##########################\n")
        
        self._displayMenu()
        
        while self.quitFlag:
            self.selectOption()
        
        
    def _choiceTypeNumber(self):
        num = input("Please type in a number -> ")
        self.numbers.append(float(num))
        
    def _displaySum(self):
        print (f'The sum is {np.sum(self.numbers)}')
    
    def _displayAverage(self):
        print (f'The average is {np.mean(self.numbers)}')
        
    def _displayMax(self):
        print (f'The max is {np.max(self.numbers)}')
    
    def _displayMin(self):
        print (f'The min is {np.min(self.numbers)}')
        
    def _displayAll(self):
        print (f'The numbers are {self.numbers}')
        
    def _quitProgram(self):
        self.quitFlag = False
        
    def _displayMenu(self):
        for option in self.menu:
            print (option)
    
    def _displayEmptyError(self):
        print ('This option is not valid because no numbers have been inserted')
        self.selectOption()
    
    def selectOption(self):
        if self.numbers:
            self.valid = True
        
        choice = input('Please select an option \n').upper()
        if choice not in self.menuInputOptions:
            print ('Entry not a valid option, please choose from the following:')
            print (self.menuInputOptions)
            self.selectOption()
        
        if choice in ['S', 'A', 'H', 'L'] and not self.valid:
            choice = None
            self._displayEmptyError()
        
        if choice == 'G':
            self._choiceTypeNumber()
        elif choice == 'S':
            self._displaySum()
        elif choice == 'A':
            self._displayAverage()
        elif choice == 'H':
            self._displayMax()
        elif choice == 'L':
            self._displayMin()
        elif choice == 'D':
            self._displayAll()
        elif choice ==  'M':
            self._displayMenu()
        elif choice == 'Q':
            self._quitProgram()
            
test = SomeClassName()