Как предотвратить повторную печать результата в Python - PullRequest
0 голосов
/ 06 мая 2020

Он отлично работает при вводе собственного числа. Однако, поскольку я игнорирую main (), чтобы проверить первую функцию и узнать результат, напечатайте дважды, когда n_item = 15.

def fun_function(n_items, cost_per_item=27, discount_percent=10, discount_threshold=20):
    """Return the total cost"""
    cost = n_items * cost_per_item  # line 1
    if n_items > discount_threshold:    # line 2
        cost = cost * (1 - discount_percent / 100)  # line 3
        print('{} items cost ${:.2f}'.format(n_items, cost))
    return cost

def main():
    """Compute and print the total cost of a number of items"""
    n_items = int(input("Number of items? "))
    fun_function(n_items, cost_per_item=27, discount_percent=10, discount_threshold=20)

# main()


cost = fun_function(5, 31, 15, 10)
print('5 items cost ${:.2f}'.format(cost))

cost = fun_function(15, 31, 15, 10)
print('15 items cost ${:.2f}'.format(cost))

>>>
5 items cost $155.00
15 items cost $395.25
15 items cost $395.25

1 Ответ

0 голосов
/ 06 мая 2020

Вы можете поместить печать в функцию, где вы всегда получаете печать

    def fun_function(n_items, cost_per_item=27, discount_percent=10, discount_threshold=20):
        """Return the total cost"""
        cost = n_items * cost_per_item  # line 1
        if n_items > discount_threshold:    # line 2
            cost = cost * (1 - discount_percent / 100)  # line 3

        return cost

    def main():
        """Compute and print the total cost of a number of items"""
        n_items = int(input("Number of items? "))
        disc_threshold=10
        cost = fun_function(n_items, cost_per_item=27, discount_percent=10, discount_threshold=disc_threshold)
        if n_items > disc_threshold:
             print('{} items cost ${:.2f}'.format(n_items, cost))

Таким образом, если вы вызываете:

cost = fun_function(5, 31, 15, 10)

cost = fun_function(15, 31, 15, 10)

>>>
5 items cost $155.00
15 items cost $395.25

Вы должны различать поведение вашей функции и того, что вы делаете из нее, например, этот print, который не является частью функции, поэтому его не следует рассматривать как «непредвиденное поведение».

--- EDIT ----

Если вы используете текущую реализацию, описанную выше, запустите main() и введите 15, вы получите желаемый результат.

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