为何无法在函数中使用raw_input?Python代码类型错误排查
解决raw_input使用疑问与代码类型错误问题
首先,咱们拆解下你遇到的两个核心问题:
1. 为什么会出现类型错误?
你看到的TypeError: unsupported operand type(s) for -=: 'str' and 'int'报错,根源很明确:raw_input()获取的所有输入都是字符串类型,但你的函数(比如rental_car_cost)需要整数来做算术运算。
举个例子:你输入的days是字符串,执行cost = days * 40时,Python会把字符串重复40次(比如输入"3"会变成一串"3"),后续的cost -= 50就会尝试用字符串减整数,这显然不符合运算规则,所以触发报错。
2. 为何“无法在函数中使用raw_input”?
其实**raw_input()完全可以在函数里使用**,你可能是碰到了这两种情况:
- 如果你用的是Python 3:
raw_input()已经被重命名为input()了,这时候写raw_input会报NameError,让你误以为不能用; - 你的代码里
raw_input是写在全局作用域,不是函数内,但这不代表函数里不能用——比如你可以把输入逻辑直接整合到trip_cost函数里,示例如下:
def trip_cost(): city = raw_input("Which city will you stay in ") days = int(raw_input("How long is the stay ")) spending_money = int(raw_input("How much is your spending budget ")) return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money trip_cost()
3. 修正你的代码
针对当前的报错,只需要把raw_input获取的数值类输入转换成整数即可,同时我帮你修正了拼写错误(你写的spening budget应该是spending budget):
def hotel_cost(nights): return 140 * nights def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost(days): cost = days * 40 if days >= 7: cost -= 50 elif days >= 3: cost -= 20 return cost def trip_cost(city, days, spending_money): return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money city = raw_input("Which city will you stay in ") # 将输入转换为整数类型 days = int(raw_input("How long is the stay ")) spending_money = int(raw_input("How much is your spending budget ")) print trip_cost(city, days, spending_money)
如果是Python 3环境,记得把所有raw_input()替换成input(),同时print要改成函数形式print(...):
# Python 3适配版本 def hotel_cost(nights): return 140 * nights def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost(days): cost = days * 40 if days >= 7: cost -= 50 elif days >= 3: cost -= 20 return cost def trip_cost(city, days, spending_money): return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money city = input("Which city will you stay in ") days = int(input("How long is the stay ")) spending_money = int(input("How much is your spending budget ")) print(trip_cost(city, days, spending_money))
内容的提问来源于stack exchange,提问作者Somil Varshney
相关产品推荐
相关产品推荐

