Python零基础学习者求助:Codecademy项目中TypeError错误解析
解决你的Python TypeError问题
嘿,别慌!这个错误其实是个超容易踩的语法小坑,我来给你掰扯清楚~
错误原因分析
你看到的TypeError: bad operand type for unary +: 'str',问题全出在你写的=+上!
在Python里,正确的加法赋值运算符是+=,而你写的=+会被Python拆解成两部分:
- 首先是一元运算符
+(用来给数值取正) - 然后是赋值运算符
=
但你这里右边的是字符串(比如lovely_loveseat_description),字符串根本不支持一元+操作,所以Python直接抛出了错误。而且不止第17行,你代码里所有的customer_one_total =+ ...和customer_one_itemization =+ ...都是同样的问题。
修正后的代码
把所有的=+改成+=就搞定了,修正后的代码如下:
lovely_loveseat_description = """Lovely Loveseat. Tufted polyester blend on wood. 32 inches high X 40 inches wide X 30 inches deep. Available in Red or White.""" lovely_loveseat_price = 254.00 stylish_settee_description = """Stylish Settee. Faux leather on birch. 29.50 inches high X 54.75 inches wide X 28 inches deep. Available only in Black.""" stylish_settee_price = 150.50 luxurious_lamp_description = "Luxurious Lamp. Glass and iron. 36 inches tall. Available in Brown with a Stylish Beige shade." luxurious_lamp_price = 52.15 #sales tax variable. sales_tax = .088 #base shopping cart total value. customer_one_total = 0 #shopping cart contents variable. customer_one_itemization = "" #shopping area. customer_one_total += lovely_loveseat_price customer_one_itemization += lovely_loveseat_description customer_one_total += luxurious_lamp_price customer_one_itemization += luxurious_lamp_description customer_one_tax = customer_one_total * sales_tax customer_one_total += customer_one_tax print("Customer One Items:") print(customer_one_itemization) print("Customer One Total Cost:") print(customer_one_total)
额外小提示
如果想让输出的总价更美观(保留两位小数,符合货币格式),可以把最后一行打印代码改成:
print(f"Customer One Total Cost: ${customer_one_total:.2f}")
这样会输出更友好的Customer One Total Cost: $333.09。
内容的提问来源于stack exchange,提问作者Tyler Wishart
相关产品推荐
相关产品推荐

