Python - цикл while внутри функции не дает согласованных результатов - PullRequest
0 голосов
/ 07 марта 2019

Новое в кодировании здесь.Я создал простую программу для класса, которая позволяет пользователю получить стоимость доставки пакета Flate Rate.Цель состояла в том, чтобы включить функции в программу (функции в 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 голосов
/ 07 марта 2019

Вам не нужно

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

Ваша функция должна просто передать выполнение на main() автоматически, но если вы хотите поместить что-то туда, чтобы сделать это явным, вы можете поместить return здесь.

Вариант 1:

# Allow the user to get back to the main menu(main function)
str(input('\nPress enter to return to main menu'))
# program will automatically go back to Main()

Вариант 2:

# Allow the user to get back to the main menu(main function)
str(input('\nPress enter to return to main menu'))
return # explicitly say to end this call to your function

ОБНОВЛЕНИЕ:

Вы также не спрашиваетеПользователь для ввода каждый раз, но получить его один раз перед циклом.Вот ваш код с парой изменений:

def main():
    while True:  # loop forever
        # 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())
        if selection == 'C':
            CalculateCost()
        elif selection == 'D':
            DisplayInfo()
        elif selection == 'X':
            print('\nThanks for choosing Box and Go!')
            break # end our forever loop


# 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
    input('Press enter to return to main menu: ')


# 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)
    input('\nPress enter to return to main menu')
    return


# 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()
0 голосов
/ 07 марта 2019

Это прекрасная возможность начать больше узнавать о переменной области видимости!По сути, выборка не является глобальной переменной, и когда вы устанавливаете ее значение в 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», в конечном итоге приведет к ошибке вашей программы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...