我的 Python 程序中的列表无法正常工作

The list in my Python program will not work properly

我无法在代码中将乘客附加到我的列表中。我得到的错误是,即使在 class Buss 中定义了列表 passengers 也没有定义。任何人都可以帮忙解决这个问题。下一个菜单功能还没有定义,所以可以等待。

我也不确定我是否正确设置了菜单循环。我是 Python 的新手,我是根据分发的代码 shell 构建的。

import replit
from getkey import getkey, keys


#MENU FUNCTIONS : these are the functions used for the menu

#menuOptions 0
def add_passenger():
  replit.clear()
  passenger_age = int(input("How old is the passenger you wish to add? "))
  print (passenger_age)
  passengers.append(passenger_age)
  input("Press enter to go back")

#menuOptions 1
def print_bus():
  replit.clear()
  print("Here is the age of all passengers")
  input("Press enter to go back")

#menuOptions 2
def calc_total_age():
  replit.clear()
  print("Here is the total age of all passengers")
  input("Press enter to go back")

#defining a class for the passenger list
class Buss:
  passengers = []
  number_of_passengers = 0


#The main part of the program where the menu system is. From here the functions are called.
  def run(self):
    menuOptions = ["Add a passenger\t\t\t\t\t\t\t", "Show the age of all passengers\t\t\t", "Show the total age of all passengers \t", "Exit simulator\t\t\t\t\t\t\t"]
    menuSelected = 0

    while(True):
      replit.clear()
      print("Welcome to MyBusTravels bussimulator, please choose what you want to do:")
      print("\x1b[?25l")

      if menuSelected == 0:
        print(menuOptions[0] + "<--")
        print(menuOptions[1])
        print(menuOptions[2])
        print(menuOptions[3])
      elif menuSelected == 1:
        print(menuOptions[0])
        print(menuOptions[1] + "<--")
        print(menuOptions[2])
        print(menuOptions[3])
      elif menuSelected == 2:
        print(menuOptions[0])
        print(menuOptions[1])
        print(menuOptions[2] + "<--")
        print(menuOptions[3])
      elif menuSelected == 3:
        print(menuOptions[0])
        print(menuOptions[1])
        print(menuOptions[2])
        print(menuOptions[3] + "<--")

      keyPressed = getkey()
      if keyPressed == keys.DOWN and menuSelected + 1 != len(menuOptions):
        menuSelected += 1
      elif keyPressed == keys.UP and menuSelected >= 1:
        menuSelected -=1
      elif keyPressed == keys.ENTER:
        if menuSelected == 0:
          add_passenger()
        elif menuSelected == 1:
          print_bus()
        elif menuSelected == 2:
          calc_total_age()
        elif menuSelected == 3:
          print("\x1b[?25h")
          break


class Program:
  def __init__(self, *args):
    minbuss = Buss()
    minbuss.run()

    replit.clear()
    input("Simulator exited, press Enter to continue . . . ")
    replit.clear()

if __name__ == "__main__":
  my_program = Program()```

现在你的方法add_passenger()对其中​​的class公交车和乘客名单一无所知。

您可以将列表作为参数传递

def add_passenger(passengers):

然后调用它

if menuSelected == 0:
          add_passenger(self.passengers)