Python - цикл while внутри функции не дает согласованных результатов

Я столкнулся с этой проблемой, и я решил ее таким образом, я использовал SCSS, чтобы не повторять одинаковые числа по коду. Приведенный ниже код просто перемещает элемент вправо, уменьшая масштаб, чтобы переустановить его.

$originalWidth: 100px;
$rate: 0.5;

parent {
  width: $originalWidth;
}

parent > div {
  transform: scale(1);
}

parent:hover {
  width: $originalWidth*$rate;
}

parent:hover > div {
  transform: translateX(($originalWidth * ($rate - 1))/2) scale($rate); /* the order matters*/
}

Вы можете избавиться от SCSS только с использованием переменных CSS и calc(), если хотите.

0
задан tromegatron 7 March 2019 в 00:33
поделиться

2 ответа

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

0
ответ дан rgk 7 March 2019 в 00:33
поделиться

Вам не нужно

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
ответ дан Reedinationer 7 March 2019 в 00:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: