It works fine when make my own input number. However, as I ignore main() to check the first function and find out the result print twice when 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
You could put the print on the function where you always get a print
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))
This way if you call:
cost = fun_function(5, 31, 15, 10)
cost = fun_function(15, 31, 15, 10)
>>>
5 items cost $155.00
15 items cost $395.25
You have to make a difference between the behaviour of your function and what you do out of it, like that print, which is not part of the function so it shouldnt be considered as "not expected behaviour".
---EDIT----
If you use the current implementetion written above and run main()
and introduce 15, you'll get desired output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.