TECHNOLOGIESTieInn Technologies

Functions

Python · 15 questions

Short notes

Key idea

A function packages steps under a name so you can reuse them. Inputs come in as parameters; the result goes out with return.

Syntax

def add_tax(amount, rate=0.18):
    # a docstring in triple quotes goes here

    return round(amount * (1 + rate), 2)

add_tax(100)            # 118.0
add_tax(100, rate=0.05) # 105.0
  • Default values make a parameter optional.
  • Keyword arguments (rate=0.05) make calls readable.

Example

def grade(score):
    if score >= 90:
        return "A"
    if score >= 75:
        return "B"
    return "C"

print([grade(s) for s in [95, 80, 60]])  # ['A', 'B', 'C']

Traps

  • No return means the function returns None. print inside a function isn't the same as returning.
  • Variables made inside a function vanish when it ends.
  • Never use a list or dict as a default: def f(x=[]) shares one list across calls. Use None and create it inside.
  • return ends the function immediately; code after it doesn't run.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Functions

  1. Question 1easy

    A function prints a value but has no return. What does calling it give back?

  2. Functions

  3. Question 2easy

    What does this print?

    def gst_price(price, rate=0.18):
        return round(price * (1 + rate), 2)
    
    print(gst_price(500) + gst_price(500, rate=0))
  4. Functions

  5. Question 3hard

    What does this print?

    def add_item(item, items=[]):
        items.append(item)
        return items
    
    add_item("a")
    print(len(add_item("b")))
  6. Functions

  7. Question 4medium

    What does this print?

    total = 10
    
    def add_five():
        total = 5
        return total
    
    add_five()
    print(total)
  8. Functions

  9. Question 5easy

    A script calls with_gst(1999) on line 1 and defines def with_gst(price): on line 5. What happens when it runs?

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.