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
returnmeans the function returnsNone.printinside 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. UseNoneand create it inside. returnends 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 →
- Question 1easy
A function prints a value but has no
return. What does calling it give back? - 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)) - Question 3hard
What does this print?
def add_item(item, items=[]): items.append(item) return items add_item("a") print(len(add_item("b"))) - Question 4medium
What does this print?
total = 10 def add_five(): total = 5 return total add_five() print(total) - Question 5easy
A script calls
with_gst(1999)on line 1 and definesdef with_gst(price):on line 5. What happens when it runs?
Functions
Functions
Functions
Functions
Functions
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.