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

罗马数字转整数Python代码输入赋值错误排查与修正问询

问题分析与修复:罗马数字转整数的输入赋值错误

Hey there, let's break down what's going wrong with your Roman numeral conversion code and fix it up.

The Root Problem

Your roman_value function is designed to accept a roman parameter (the numeral string to convert), but it's ignoring this parameter entirely. Instead, it adds an unnecessary input() call inside the function—this not only breaks the automated testing in your __main__ block (since it'll prompt for manual input every time you call the function), but the input value you capture isn't even used in the conversion logic! You store it in romanSymbol but never assign it to the roman variable that your loop actually processes.

The Fix

All we need to do is remove that stray input() line, so the function properly uses the roman parameter passed to it. Here's the corrected code:

def roman_value(roman):
    roman_values = (('I',1), ('IV',4), ('V',5), ('IX',9),('X',10),('XL',40),('L',50),('XC',90),('C',100), ('CD', 400), ('D', 500), ('CM', 900), ('M',1000))
    total = 0
    # Removed the unnecessary input statement—now using the passed `roman` parameter
    for symbol, value in reversed(roman_values):
        while roman.startswith(symbol):
            total += value
            roman = roman[len(symbol):]
    return total

if __name__=='__main__':
    for value in "MCMXC", "MMVIII", "MDCLXVI", "":
        print('%s = %i' % (value, roman_value(value)))

What Changed?

  • We got rid of the romanSymbol = input(...) line entirely. This lets the function focus on its core job: converting the input parameter it receives, rather than prompting for manual input.
  • Now when you run the script, the for loop in the main block will correctly pass each test numeral (like "MCMXC" or "MMVIII") to roman_value, and you'll get the expected output without any interruptions.

Expected Output

When you run the corrected code, you'll see this in your terminal:

MCMXC = 1990
MMVIII = 2008
MDCLXVI = 1666
 = 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:48:04