python - 变量未定义——Python——条件语句
问题描述
所以我遇到了这段代码的问题。当我运行它时,它指出变量 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)
解决方案
正如对您问题的评论建议您应该cost_of_rental
在条件旁边声明变量。目前,如果您的条件都不为真,则您的cost_of_rental
变量未定义。换句话说 - 只有当您满足任何条件时,您才能定义它。在您的条件中添加cost_of_rental = 0
开头或else
(不是elif
)语句应该可以解决您的问题。
推荐阅读
- python - 将每个列表元素与唯一的状态组合配对
- java - 为什么 java.lang.StackOverflowError: null 当我尝试打印我的实体
- python - 将小时和分钟添加到已保存的 django DateTimeField
- reactivesearch - 带有 cookie 身份验证的 Reactivesearch proxylike 后端
- java - 使用 GSON 将 JSON 字符串转换为 Java 对象
- c# - C# Directory.Move 但对于已经存在的文件夹 - 如何在不创建全新目录的情况下使用此方法或类似方法?
- c# - c# selenium if else 检查
- python - Azure Python 计费 API
- ios - IOS-Deploy 和 iOS 开发者证书
- c# - 默认 CLR 主机为每个域提供 2 秒的“ProcessExit 事件处理程序”?