0
0
Pythonprogramming~15 mins

Lambda vs regular functions in Python - Hands-On Comparison

Choose your learning style9 modes available
Lambda vs Regular Functions
๐Ÿ“– Scenario: Imagine you are organizing a small party and want to quickly calculate the cost of snacks based on quantity. You will use Python functions to do this calculation in two ways: with a regular function and with a lambda function.
๐ŸŽฏ Goal: Build two functions that calculate the total cost of snacks by multiplying the quantity by the price per snack. One function will be a regular function, and the other will be a lambda function. Then, compare their outputs.
๐Ÿ“‹ What You'll Learn
Create a regular function called calculate_cost that takes quantity and price_per_snack as parameters and returns the total cost.
Create a lambda function called calculate_cost_lambda that does the same calculation.
Use both functions to calculate the cost for 5 snacks priced at 2 each.
Print the results from both functions.
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Functions help automate repetitive calculations like pricing items in a store or calculating bills quickly.
๐Ÿ’ผ Career
Understanding both regular and lambda functions is important for writing clean, efficient code in many programming jobs.
Progress0 / 4 steps
1
Create a regular function to calculate cost
Write a regular function called calculate_cost that takes two parameters: quantity and price_per_snack. It should return the product of these two parameters.
Python
Need a hint?

Use the def keyword to create a function. Multiply quantity by price_per_snack and return the result.

2
Create a lambda function to calculate cost
Create a lambda function called calculate_cost_lambda that takes quantity and price_per_snack as inputs and returns their product.
Python
Need a hint?

Assign a lambda function to calculate_cost_lambda. The lambda should take two parameters and return their multiplication.

3
Calculate cost using both functions
Use the regular function calculate_cost and the lambda function calculate_cost_lambda to calculate the cost for 5 snacks priced at 2 each. Store the results in variables cost_regular and cost_lambda respectively.
Python
Need a hint?

Call both functions with arguments 5 and 2, and save their results in cost_regular and cost_lambda.

4
Print the results
Print the values of cost_regular and cost_lambda on separate lines.
Python
Need a hint?

Use two print statements to show the values of cost_regular and cost_lambda.