Code / Python for Beginners / Unit 5: Functions, text and your project

Functions फ़ंक्शन

Lesson 12 of 14 · about 15 minutes · def, return and default arguments.

⚡ 0 XP

Step 1 of 2

Make your own command

function⚙100118

A function is a named recipe you can use again and again. Define it with def, give it parameters in brackets, and send the answer back with return:

def with_gst(price):
return price * 1.18

Now with_gst(100) gives 118.0. The code inside does not run until you call the function.

return is not the same as print: print only shows the answer on screen, while return hands it back so other code can use it, e.g. bill = with_gst(250).

Example
def square(n):
    return n * n

print(square(4))
big = square(12) + 1
print(big)

🎯 Challenge: GST calculator +20 XP

Write a function with_gst(price) that returns the price plus 18% GST, rounded to 2 decimals. So with_gst(100) returns 118.0 and with_gst(250) returns 295.0. Use return, not print.

Try twice to unlock the solution (0/2)

main.pyCtrl ⏎
Output

What your program prints appears here.

Checklist

Press Run to check your code.

  • with_gst(100) returns 118
  • with_gst(250) returns 295
  • Rounds to 2 decimals
Lesson notes (text version)

1. Make your own command

A function is a named recipe you can use again and again. Define it with def, give it parameters in brackets, and send the answer back with return:

def with_gst(price):
return price * 1.18

Now with_gst(100) gives 118.0. The code inside does not run until you call the function.

return is not the same as print: print only shows the answer on screen, while return hands it back so other code can use it, e.g. bill = with_gst(250).

                def square(n):
    return n * n

print(square(4))
big = square(12) + 1
print(big)
              

Challenge: GST calculator

Write a function with_gst(price) that returns the price plus 18% GST, rounded to 2 decimals. So with_gst(100) returns 118.0 and with_gst(250) returns 295.0. Use return, not print.

2. Default arguments

A parameter can have a default value that is used when the caller leaves it out:

def chai_bill(cups, price=15):

  • chai_bill(3) uses price 15
  • chai_bill(3, 20) uses price 20

Parameters with defaults must come after the ones without.

                def chai_bill(cups, price=15):
    return cups * price

print(chai_bill(3))
print(chai_bill(3, 20))
              

Challenge: Auto-rickshaw fare

Write auto_fare(km, rate=12, min_fare=30) that returns km × rate, but never less than min_fare. (Sample rates.) So auto_fare(5) is 60, auto_fare(1) is 30, auto_fare(5, 15) is 75 and auto_fare(2, 10, 25) is 25.

Search by task, format or tool name.