Новое в кодировании здесь.Я создал простую программу для класса, которая позволяет пользователю получить стоимость доставки пакета 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()