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

为何输入不同值却输出相同?Python脚本问题求助

问题分析与修复

你的脚本出现所有输入项输出结果一致的问题,根源在于条件判断的顺序逻辑错误。

原代码里,elif int(e[0]) >= 3这个条件排在所有更高阈值的判断前面,只要输入的数值≥3,就会直接触发这个分支并输出/30,后面的≥5、≥9等条件完全没有执行的机会。比如你输入的5、10、150都满足≥3,所以全部输出同一个结果。

修复后的代码

PFX = input("What's the customer prefix: ")
EXTSNAT = input("Enter the number of external SNAT addresses needed: ")
EXTVIP = input("How many addresses for public VIPs are needed: ")
INTSNAT = input("Enter the number of internal SNAT addresses needed: ")
INTVIP = input("Enter the number of internal VIP addresses needed: ")
PLATFORM_POOL = input("How many usable IPs should be allocated to platform pool: ")

list_to_check = [
    [EXTSNAT, "External SNAT"], 
    [EXTVIP, "External VIP"], 
    [INTSNAT, "Internal SNAT"], 
    [INTVIP, "Internal VIP"], 
    [PLATFORM_POOL, "Platform Pool"]
]

def address_blocks(check_list):
    # 按阈值从高到低定义CIDR对应关系
    cidr_mapping = [
        (129, "/24"),
        (65, "/25"),
        (33, "/26"),
        (17, "/27"),
        (9, "/28"),
        (5, "/29"),
        (3, "/30"),
        (0, "/31")
    ]

    for item in check_list:
        count = int(item[0])
        for threshold, cidr in cidr_mapping:
            if count >= threshold:
                print(f"{item[1]}: Use {cidr}")
                break

address_blocks(list_to_check)

关键修改点

  1. 调整判断顺序:把阈值从高到低排列,确保大数值能匹配到对应的CIDR,不会被低阈值的条件提前拦截。
  2. 优化代码结构:用列表存储阈值和CIDR的对应关系,比一堆if-elif更简洁易维护。
  3. 避免内置名冲突:把函数参数名从list改成check_list,避免覆盖Python内置的list类型。

现在输入5、5、10、10、150时,会输出预期的不同结果:

External SNAT: Use /29
External VIP: Use /29
Internal SNAT: Use /28
Internal VIP: Use /28
Platform Pool: Use /24

内容的提问来源于stack exchange,提问作者Sigurd Bakaas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:55:14