如何在Python中将不同的年龄加在一起

问题描述 投票:0回答:1

我正在做一项作业,要求我创建一个公交车模拟器,要求用户输入所有乘客的年龄,并且该程序应该将所有年龄加在一起。如果用户输入的年龄超过 24 岁,程序也会停止。该程序应该循环询问年龄,然后添加所有年龄。需要帮助,如果有人知道怎么做请告诉我。

这有点像我使用的方法,但我不知道该怎么办

class Buss:
        passengers = []
        total_passengers = 0

    def run(self):  
        print("Hello, welcome to the bus simulator")
        

    def add_passanger(self):
       

    def print_buss(self):
        

    def calc_total_age(self):
python variable-assignment
1个回答
0
投票

潜在的实施:

class Bus:
    def __init__(self):
        self.passengers = []
        self.total_passengers = 0

    def run(self):
        print("Hello, welcome to the bus simulator")

    def add_passenger(self, age):
        self.passengers.append(age)
        # Update total number of passengers
        self.total_passengers = len(self.passengers)

    def print_bus(self):
        print("Total Passengers on the bus: ", len(self.passengers))

    def calc_total_age(self):
        print("Total Age of Passengers: ", sum(self.passengers))
        print("Average Age of Passengers: ", sum(self.passengers)/self.total_passengers)


if __name__ == "__main__":
    bus = Bus()
    bus.run()

    count = 0
    while count < 5:
        age = input("Enter passenger age (or 'q' to quit): ")
        if age.lower() == 'q':
            break
        try:
            age = int(age)
            bus.add_passenger(age)
            count += 1
        except ValueError:
            print("Invalid input. Please enter a valid age.")

    bus.print_bus()
    bus.calc_total_age()

© www.soinside.com 2019 - 2024. All rights reserved.