首页 > 解决方案 > 变量未定义——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)

标签: pythonpython-3.xconditional-statements

解决方案


正如对您问题的评论建议您应该cost_of_rental在条件旁边声明变量。目前,如果您的条件都不为真,则您的cost_of_rental变量未定义。换句话说 - 只有当您满足任何条件时,您才能定义它。在您的条件中添加cost_of_rental = 0开头或else(不是elif)语句应该可以解决您的问题。


推荐阅读