Python 尽管初始化,try-except 函数递归将值存储为列表

Python try-except function recursion stores value as list despite initialization

我正在做一个练习,涉及在 Python 中使用 try-except 探索异常处理的使用。我正在使用它们来检查用户输入的值是浮点数还是其他值(例如字符串)。如果该值不是浮点数,则会触发异常并递归调用该函数。这有效,但是当我打印并 return 值时,该值是浮点数和字符串的列表,尽管尝试在本地和全局初始化为浮点数。我是 Python 的新手,与 C/C++ 相比,我确实不习惯它的细微差别。我可能遗漏了一些微不足道的东西,但我无法确定原因。程序如下:

def check_cost():
    fuel_cost = 0.0
    fuel_cost = input("What is the cost per unit fuel (in $ per gallons)? ")
    try:
        fuel_cost = float(fuel_cost)
    except ValueError as e:
        print("\nThe value has to be numeric. Please try again.")
        check_cost()
    print(fuel_cost)
    return fuel_cost

def check_distance():
    work_distance = 0.0
    work_distance = input("What is the one-way distance to work (in miles)? ")
    try:
        work_distance = float(work_distance)
    except ValueError as e:
        print("\nThe value has to be numeric. Please try again.")
        check_distance()
    print(work_distance)
    return work_distance

def check_level():
    fuel_level = 0.0
    fuel_level = input("What is the current amount of fuel in your tank (in gallons)? ")
    try:
        fuel_level = float(fuel_level)
    except ValueError as e:
        print("\nThe value has to be numeric. Please try again.")
        check_level()
    print(fuel_level)
    return fuel_level

def check_rate():
    consumption_rate = 0.0
    consumption_rate = input("What is your fuel economy (in miles per gallon)? ")
    try:
        consumption_rate = float(consumption_rate)
    except ValueError as e:
        print("\nThe value has to be numeric. Please try again.")
        check_rate()
    print(consumption_rate)
    return consumption_rate  

fuel_cost = 0.0
work_distance = 0.0
fuel_level = 0.0
consumption_rate = 0.0

name = input("What is your user name? ")

print("\nHello, %s! Let's get started!" % name)

check = True

while check:
    # cost per unit of fuel
    #fuel_cost = float(input("What is the cost per unit fuel (in $ per gallons)? "))
    fuel_cost = check_cost()
    # one-way distance to work
    #work_distance = float(input("What is the one-way distance to work (in miles)? "))
    work_distance = check_distance()
    # current amount of fuel in gas tank
    #fuel_level = float(input("What is the current amount of fuel in your tank (in gallons)? "))
    fuel_level = check_level()
    # drivable distance per unit of fuel
    #consumption_rate = float(input("What is your fuel economy (in miles per gallon)? "))
    consumption_rate = check_rate()
    # acceptable level of fuel:
    threshold = work_distance / consumption_rate

loop_1 = True

while loop_1:
    review = input("Would you like to review the values? (Y/N) ")
    if review == 'Y' or review == 'y':
        print("\nfuel cost = %.2f" % fuel_cost)
        print("work distance = %.2f" % work_distance)
        print("fuel level = %.2f" % fuel_level)
        print("consumption rate = %.2f" % consumption_rate)
        loop_1 = False
    elif review == 'N' or review == 'n':
        print("\nOkay, continuing...")
        loop_1 = False
    else:
        print("\nInvalid input. Please enter either of Y/N")

loop_2 = True

while loop_2:
    question = input("Would you like to re-enter these values? (Y/N)")
    if question == 'Y' or question == 'y':
        check = True
        loop_2 = False
    elif question == 'N' or question == 'n':
        check = False
        loop_2 = False
    else:
        print("\nInvalid input. Please enter either of Y/N")

# Reporting Strings:
low = '\nYou will not make it to work without refueling first!\n'
exact = '\nYou have just enough fuel to get to work, but will not make it home.\n'
some_extra ='\nYou will need to refuel in the near future...\n'
surplus = '\nYou have plenty of fuel, have a safe drive to work today!\n'

if fuel_level < threshold:
    print(low)
elif fuel_level == threshold:
    print(exact)
elif fuel_level > threshold and fuel_level < threshold+1 :
    print(some_extra)
else:
    print(surplus)

打印输出如下:

What is your user name? Leigh

Hello, Leigh! Let's get started!

What is the cost per unit fuel (in $ per gallons)? five

The value has to be numeric. Please try again.

What is the cost per unit fuel (in $ per gallons)? 5
5.0
five

What is the one-way distance to work (in miles)? five

The value has to be numeric. Please try again.

What is the one-way distance to work (in miles)? 5
5.0
five

What is the current amount of fuel in your tank (in gallons)? five

The value has to be numeric. Please try again.

What is the current amount of fuel in your tank (in gallons)? 5
5.0
five

What is your fuel economy (in miles per gallon)? five

The value has to be numeric. Please try again.

What is your fuel economy (in miles per gallon)? 5
5.0
five

Traceback (most recent call last):

threshold = work_distance / consumption_rate

TypeError: unsupported operand type(s) for /: 'str' and 'str'

以后,请花时间 post 对您的问题进行 最少的 陈述。换句话说,调试您的代码并找到导致问题的特定段。通常你会发现解决方案在这个过程中出现。

问题是您的递归函数由于作用域的原因无法按预期工作。在您的 check_rate 函数中,check_rate()except 循环中的 运行,然后将其结果丢弃,因为您没有将它们存储在任何地方。然后函数继续并使用旧的字符串变量 ("five").

以下是定义函数的正确方法:

def check_rate():
    while True:
        try:
            consumption_rate = float(input("What is your fuel economy (in miles per gallon)? "))
        except ValueError as e:
            print("\nThe value has to be numeric. Please try again.")
            continue
        else:
            break
    return consumption_rate

check_rate()

另请参阅:Asking the user for input until they give a valid response