You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codetown城市公交Python程序循环条件调试及输入验证求助

Codetown公交统计程序问题求助

我已经完成了Codetown城市公交统计需求的Python开发,程序能输出示例正确结果,但存在两个问题:

  • 循环未处理最后一站(所有乘客需下车),总是在倒数第二站结束;
  • 无法实现无效输入的验证功能。

需求背景

Codetown市长需要公交运营数据,程序需实现以下功能:

  1. 司机输入路线号、站点总数、首站候车乘客数;
  2. 后续站点中,非最后一站需输入下车人数和候车人数,最后一站仅需输入下车人数;
  3. 最终输出路线号、happy customers(满意乘客数)、unhappy customers(不满意乘客数)及两者比值(保留两位小数,无不满意乘客时为0.00)。

我尝试修改循环范围为num_stops+1,但会错误询问最后一站的候车人数,现附上代码寻求协助:

def collect_data():
    route_number = int(input("Please enter the route number: "))
    num_stops = int(input("Please enter the number of stops on this route: "))
    passengers_at_start = int(input("How many passengers were waiting for the bus at stop 1: "))
    return route_number, num_stops, passengers_at_start

def calculate_customers(num_stops, passengers_at_start):
    happy_customers = passengers_at_start
    unhappy_customers = 0

    for stop in range(2, num_stops):
        passengers_leaving = int(input(f"How many passengers left at stop {stop}: "))
        passengers_waiting = int(input(f"How many passengers were waiting for the bus at stop {stop}: "))

        passengers_at_start = passengers_at_start - passengers_leaving
        available_space = 35 - passengers_at_start

        if passengers_waiting > available_space:
            happy_customers += available_space
            unhappy_customers += passengers_waiting - available_space
            passengers_at_start = 35
        else:
            happy_customers += passengers_waiting
            passengers_at_start += passengers_waiting

    return happy_customers, unhappy_customers

def main():
    route_number, num_stops, passengers_at_start = collect_data()
    happy_customers, unhappy_customers = calculate_customers(num_stops, passengers_at_start)

    print(f"Route number: {route_number}")
    print(f"Happy customers: {happy_customers}")
    print(f"Unhappy customers: {unhappy_customers}")
    print(f"Ratio of happy customers to unhappy customers: {happy_customers/unhappy_customers:.2f}" if unhappy_customers > 0 else "Ratio of happy customers to unhappy customers: 0.00")


if __name__ == "__main__":
  main()

问题修复方案

1. 修复循环处理最后一站的问题

原循环range(2, num_stops)因为左闭右开特性,只会遍历到倒数第二站。调整循环范围为range(2, num_stops + 1),并在循环内判断当前是否为最后一站:如果是,只处理下车人数,无需询问候车乘客(最后一站所有乘客下车,不再上人)。

2. 添加无效输入验证功能

新增通用输入验证函数,确保用户输入为非负整数,同时补充业务逻辑验证(比如下车人数不能超过当前车上人数、首站候车人数不超过公交容量35等)。

完整修复代码

def get_valid_integer_input(prompt):
    while True:
        try:
            value = int(input(prompt))
            if value < 0:
                print("Error: Please enter a non-negative number.")
                continue
            return value
        except ValueError:
            print("Error: Please enter a valid integer.")

def collect_data():
    route_number = get_valid_integer_input("Please enter the route number: ")
    
    num_stops = get_valid_integer_input("Please enter the number of stops on this route: ")
    while num_stops < 1:
        print("Error: The number of stops must be at least 1.")
        num_stops = get_valid_integer_input("Please enter the number of stops on this route: ")
    
    passengers_at_start = get_valid_integer_input("How many passengers were waiting for the bus at stop 1: ")
    while passengers_at_start > 35:
        print("Error: The bus can only hold 35 passengers.")
        passengers_at_start = get_valid_integer_input("How many passengers were waiting for the bus at stop 1: ")
    
    return route_number, num_stops, passengers_at_start

def calculate_customers(num_stops, passengers_at_start):
    happy_customers = passengers_at_start
    unhappy_customers = 0

    for stop in range(2, num_stops + 1):
        # 验证下车人数不超过当前车上人数
        while True:
            passengers_leaving = get_valid_integer_input(f"How many passengers left at stop {stop}: ")
            if passengers_leaving > passengers_at_start:
                print(f"Error: Only {passengers_at_start} passengers are on the bus, can't have {passengers_leaving} leaving.")
            else:
                break
        passengers_at_start = passengers_at_start - passengers_leaving

        # 非最后一站处理候车乘客
        if stop != num_stops:
            passengers_waiting = get_valid_integer_input(f"How many passengers were waiting for the bus at stop {stop}: ")
            available_space = 35 - passengers_at_start

            if passengers_waiting > available_space:
                happy_customers += available_space
                unhappy_customers += passengers_waiting - available_space
                passengers_at_start = 35
            else:
                happy_customers += passengers_waiting
                passengers_at_start += passengers_waiting
        # 最后一站清空车上乘客
        else:
            passengers_at_start = 0

    return happy_customers, unhappy_customers

def main():
    route_number, num_stops, passengers_at_start = collect_data()
    happy_customers, unhappy_customers = calculate_customers(num_stops, passengers_at_start)

    print(f"\nRoute number: {route_number}")
    print(f"Happy customers: {happy_customers}")
    print(f"Unhappy customers: {unhappy_customers}")
    ratio = happy_customers / unhappy_customers if unhappy_customers > 0 else 0.00
    print(f"Ratio of happy customers to unhappy customers: {ratio:.2f}")

if __name__ == "__main__":
    main()

修复说明

  • 循环范围调整为range(2, num_stops + 1),确保覆盖最后一站;
  • 最后一站仅处理下车操作,重置车上乘客数为0;
  • 新增通用输入验证函数,拦截非整数、负数输入;
  • 补充业务逻辑验证:下车人数不超当前载客量、首站候车人数不超公交容量、站点数至少为1;
  • 优化输出格式,让结果展示更清晰。

内容的提问来源于stack exchange,提问作者Karen Stanley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:30:19