Python TypeError求助:字符串无法执行减法运算
Hey there! Let's get that mileage calculation error sorted out for your rental car cost program.
What's Causing the Error?
The traceback spells out the issue clearly: you're trying to subtract two strings (odoEnd and odoStart) using the - operator, and Python doesn't know how to perform subtraction on text values. When you use the input() function to collect user data, it always returns a string—even if the user types a number. Right now, your program is treating odometer readings like words, not numerical values.
How to Fix It
You just need to convert those input values to a numerical type (either int for whole numbers or float if your odometer uses decimals) before doing the subtraction.
Here's the quick fix for your input lines:
# Convert input strings to integers odoStart = int(input("Enter starting odometer reading: ")) odoEnd = int(input("Enter ending odometer reading: "))
If your odometer tracks fractional miles (like 12345.6), use float() instead:
odoStart = float(input("Enter starting odometer reading: ")) odoEnd = float(input("Enter ending odometer reading: "))
Make It Robust (Optional)
To handle cases where a user might type something non-numeric (like letters or symbols), add a simple error check with try/except:
try: odoStart = int(input("Enter starting odometer reading: ")) odoEnd = int(input("Enter ending odometer reading: ")) except ValueError: print("Oops! Please enter a valid number for the odometer reading.") # Exit or prompt the user again, depending on your program flow exit()
Once you make this change, your totalMiles = odoEnd - odoStart line will work as expected—you'll be subtracting two numbers instead of two strings.
内容的提问来源于stack exchange,提问作者Jordan2398213

