Python-函数内部的while循环无法产生一致的结果

时间:2019-03-07 00:33:46

标签: python function loops

此处是编码的新手。我为课堂创建了一个简单的程序,该程序使用户能够获得运输固定费用套餐的费用。目的是将函数合并到程序中(Python中的函数是我们所在的单元)。我的老师说我的程序按预期工作,但是我可以使用“ while”循环来改进它,这样,如果用户输入错误的选择,它不会突然将他们踢出程序,而是会再次提示他们进行输入。我以前在函数中使用过“ while”循环,但没有在函数中使用过,它会产生令人困惑的结果。

当我现在运行程序时,如果我不进入子菜单并首先返回主菜单,则输入“ X”退出会暂停程序。它还不再显示我的感谢消息。此外,如果我确实要进入子菜单并返回主菜单并尝试退出,则该程序会将我发送到子菜单中。最后,使用“ while”循环不会产生预期的结果,这将允许用户在不崩溃的情况下进行输入错误。任何帮助是极大的赞赏!希望我的问题有道理。

def main():
    # Create the menu text
    print('==================================')
    print('Box and Go')
    print('==================================\n')
    print('C: Calculate cost to ship a package')
    print('D: Display shipping cost information')
    print('X: Exit Application\n')
    # Allow the user to select a menu option
    selection = str(input('Enter your menu selection: ').upper())
    while selection.upper() != "X":
        if selection == 'C':
            CalculateCost()
        elif selection == 'D':
            DisplayInfo()
        elif selection == 'X':
            print('\nThanks for choosing Box and Go!')


# Declare the function that shows the shipping rates
def DisplayInfo():
    print('==================================')
    print('SHIPPING COST INFORMATION')
    print('==================================\n')
    print('All packages are flat rate shipping\n')
    print('Flat Rate Envelope\t $6.70')
    print('Small Flat Rate Box\t $7.20')
    print('Medium Flat Rate Box\t $13.65')
    print('Large Flat Rate Box\t $18.90\n')

    # Allow the user to return to the main menu
    selection = str(input('Press enter to return to main menu: ').upper())

    if selection == '':
        main()

# Declare the function that will allow the user to
# find out the total price of each shipping option with tax included
def CalculateCost():
    print('==================================')
    print('COST ESTIMATOR FOR PACKAGES')
    print('==================================\n')

    # The user will select their option here
    selection = str(input('Enter type of package to send:\n(E)nvelope, (S)mall box, (M)edium Box, (L)arge box: ').upper())

    if selection == 'E':
        subtotal = 6.70
    elif selection == 'S':
        subtotal = 7.20
    elif selection == 'M':
        subtotal = 13.65
    elif selection == 'L':
        subtotal = 18.90
    # The program will call the CalcTax function to get the tax, then add that amount
    # to the subtotal, giving them the grand total cost of shipping
    print('\nTotal Shipment Cost: $', format(CalcTax(subtotal) + subtotal, '.2f'), sep=''
          )
    # Allow the user to get back to the main menu(main function)
    main_menu = str(input('\nPress enter to return to main menu'))

    if main_menu == '':
            main()


# Declare the function that will calculate
# tax based on the shipping selection the user made,
# then pass that amount back to the CalculateCost function
# that called it
def CalcTax(number):
    subtotal = number * 0.06
    return subtotal

# Call the main function. The program executes from here
main()

2 个答案:

答案 0 :(得分:0)

这是一个开始学习更多有关可变范围的绝好机会!本质上,选择不是全局变量,并且在DisplayInfo()内设置其值时,该值实际上并没有传递回main()。而是考虑使用return将用户的输入发送回函数。

这是您的代码,其中进行了一些更改以修复无限循环:

...
    while selection.upper() != "X":
        if selection == 'C':
             CalculateCost()
        elif selection == 'D':
            selection = DisplayInfo()
        elif selection == 'X':
            print('\nThanks for choosing Box and Go!')


# Declare the function that shows the shipping rates
def DisplayInfo():
    print('==================================')
    print('SHIPPING COST INFORMATION')
    print('==================================\n')
    print('All packages are flat rate shipping\n')
    print('Flat Rate Envelope\t $6.70')
    print('Small Flat Rate Box\t $7.20')
    print('Medium Flat Rate Box\t $13.65')
    print('Large Flat Rate Box\t $18.90\n')

    # Allow the user to return to the main menu
    return str(input('Press enter to return to main menu: ').upper())

我还建议您花一些时间来了解调用堆栈(即程序中要调用的函数的深度)。当您在main()内部调用DisplayInfo()时,实际上是通过递归再次运行函数 ,因为该函数已经在该上下文之外运行。尽管堆栈的限制(实际上是众所周知的“溢出”)很高,但是从理论上讲,继续输入'D'的用户最终将导致程序出错。

答案 1 :(得分:0)

您不需要

Y

您的函数应该只是自动将执行交给Y,但是如果您想在其中放置一些内容使其明确,则可以在此处放置X

选项1:

?- write_term([1,2,3,4],[dotlists(true)]).
.(1,.(2,.(3,.(4,[]))))
true.

选项2:

main_menu = str(input('\nPress enter to return to main menu'))
if main_menu == '':
    main()

更新:

您也不是每次都要求用户输入,而是在循环之前获取一次。这是您的代码,进行了一些修改:

main()