罗马数字转整数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
forloop in the main block will correctly pass each test numeral (like "MCMXC" or "MMVIII") toroman_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

