How can I define a program of Python with optional arguments?

216    Asked by DelbertRauch in Python , Asked on Nov 23, 2023

I was designing a function by using Python in which I needed to include the total cost of a shopping cart. There were various arguments and among them, there was an Optional argument of the discount percentage that users can apply. How can I implement this particular optional argument in my function and what will the process of utilising it by the users when calling the function? 

Answered by Chloe Burgess

 For implementing an optional argument like discount percentage in the context of a Python function, you can set a default value for the argument. Here is an example of it:-

Def calculate_ total_ cost( cart_ items, discount_ percentage=0): 
Total_ cost = sum( cart_ items)
Discounted_ cost = total_cost – ( total_ cost* discount_ percentage/ 100)
Return discounted_ cost
Users can also call this above specific function without providing the ‘discount_ percentage’ argument
# Without Discount
Total_ without_ discount= calculate_ total_ cost[ 20, 30, 40])
Print( total_ without_ discount)
#With Discount
Total_ with_ discount= calculate_ total_ cost([ 20, 30, 40], discount_ percentage= 10)
Print( total_ with_ discount)

In the first above example, the default value of the discount percentage is 0, on the other hand, the default value of the discount percentage is 10%. Join the Python certification course for more information.



Your Answer

Interviews

Parent Categories