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

如何将用户输入转换为带间隔的Range对象 实现温度转换的范围生成需求

温度范围转换工具完整实现
# 单位选择校验循环
while True:
    ask = input("请选择输入的温度单位:摄氏度=1,华氏度=2 \n请输入1或2:")
    # 校验输入是否为合法数字
    if not ask.strip().isdigit():
        print("invalid,请重新输入")
        continue
    unit_opt = int(ask)
    if unit_opt in (1, 2):
        break
    print("invalid,请重新输入")

# 范围输入校验循环
while True:
    range_input = input("请输入以星号分隔的起始值、终止值、间隔值,示例:0*10*2 \n请输入:")
    parts = range_input.strip().split("*")
    # 校验输入的段数是否合法
    if len(parts) <1 or len(parts) >3:
        print("输入格式错误,请重新输入")
        continue
    # 尝试将所有输入转为浮点数
    try:
        num_parts = [float(p) for p in parts]
    except ValueError:
        print("输入值必须为数字,请重新输入")
        continue
    # 兼容不同长度的输入
    if len(num_parts) == 1:
        start = 1
        end = num_parts[0]
        interval = 2
    elif len(num_parts) ==2:
        start, end = num_parts
        interval = 2 if start < end else -2
    else:
        start, end, interval = num_parts
    # 校验间隔合法性
    if start < end and interval <=0:
        print("起始值小于终止值时,间隔必须为正数,请重新输入")
        continue
    if start > end and interval >=0:
        print("起始值大于终止值时,间隔必须为负数,请重新输入")
        continue
    if interval ==0:
        print("间隔不能为0,请重新输入")
        continue
    # 校验通过,生成温度序列
    temp_list = []
    current = start
    if start < end:
        while current < end:
            temp_list.append(current)
            current += interval
    else:
        while current > end:
            temp_list.append(current)
            current += interval
    # 温度转换逻辑
    result = []
    if unit_opt ==1:
        # 摄氏度转华氏度
        for c in temp_list:
            f = c *9/5 +32
            result.append((c, f))
        print("摄氏度 -> 华氏度 转换结果:")
        for c,f in result:
            print(f"{c}°C = {f:.2f}°F")
    else:
        # 华氏度转摄氏度
        for f in temp_list:
            c = (f -32)*5/9
            result.append((f, c))
        print("华氏度 -> 摄氏度 转换结果:")
        for f,c in result:
            print(f"{f}°F = {c:.2f}°C")
    break

功能说明

  • 单位输入支持自动校验,输入非1/2的内容会输出invalid并要求重试
  • 范围输入完全符合要求的兼容规则:
    • 输入1个值:默认起始值为1,终止值为输入值,间隔自动取2
    • 输入2个值:自动识别升降序,间隔默认取±2
    • 输入3个值:按自定义参数生成范围
  • 自动校验间隔方向合法性,不符合要求会提示重试
  • 支持浮点型温度输入,适配更通用的使用场景

测试示例

  1. 单位选择输入1,范围输入0*10*2,会生成[0,2,4,6,8]的摄氏度序列,并输出对应的华氏度值
  2. 单位选择输入2,范围输入10,会生成[1,3,5,7,9]的华氏度序列,输出对应的摄氏度值
  3. 单位选择输入1,范围输入10*2,会生成[10,8,6,4]的摄氏度序列,输出对应的华氏度值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:45:03