所以我在这段代码上遇到了问题。当我运行它时,它指出未定义变量cost_of_rental。我做错了什么?
这是我的代码:
type_car = input("Welcome to CarRental. What type of car would you like to rent? ")
rent_duration = int(input("For how many days do you wish to rent this car? "))
available_classes = ['Class B', 'Class C', 'Class D']
if type_car == 'Class B':
if rent_duration <= 6:
cost_of_rental = 27 * rent_duration
elif rent_duration <= 27:
cost_of_rental = 167 + (rent_duration-7)*25
elif rent_duration <= 60:
cost_of_rental = 662 + (rent_duration-28)*23
if type_car == 'Class C':
if rent_duration <= 6:
cost_of_rental = 34*rent_duration
elif rent_duration <= 27:
cost_of_rental = 204 + (rent_duration - 7)*31
elif rent_duration <= 60:
cost_of_rental = 810 + (rent_duration - 28)*28
if type_car == 'Class D':
if rent_duration <= 6:
print("Sorry, Class D cars cannot be rented for less than 7 days.")
elif rent_duration <= 27:
cost_of_rental = 810 + (rent_duration-28)*43
elif rent_duration <= 60:
cost_of_rental = 1136 + (rent_duration - 28)*38
print("Your total cost is: ", cost_of_rental)
答案 0 :(得分:0)
作为对问题的评论,建议您在条件旁边声明cost_of_rental
变量。当前,如果您的条件都不为True,则未定义cost_of_rental
变量。换句话说-仅在满足任何条件时才定义它。在您的条件的开头或cost_of_rental = 0
(而非else
)语句中添加elif
可以解决您的问题。
答案 1 :(得分:-1)
由于您的if
/ elif
结构没有else
块,因此代码中的某些路径不会为变量cost_of_rental
赋值。如果这些路径永远不能被有效的rent_duration
所采用,我建议通过引发ValueError
来表明rent_duration
无效来处理它。
请注意,您的外部if
语句同样适用-如果type_car
不是您检查过的选项之一,则我认为这意味着输入无效,因此引发{ {1}}是适当的。引发错误意味着您的代码将无法正常继续,因此将无法到达底部的print语句(当输入无效时,这就是您想要的)。
如果您想向用户显示友好的错误消息,请使用ValueError
/ try
。通常,仅catch
错误消息不是一个好主意,因为您的代码将继续使用无效数据执行,这通常意味着您将获得没有意义的结果(例如,打印错误消息,然后仍然打印总费用。
print