⚡0 XP🔥0

Ch 2 · Functions | फ़ंक्शन

Lesson 2 of 10 ⏱ 3 min read ✎ 1 exercises ❓ 5-question quiz ▶ Runs Python

Built-in, module and user-defined functions, arguments and parameters (positional, default, keyword), return values, flow of execution and scope of variables (local and global).

Types of functions#

  1. Built-in: len(), max(), input().
  2. Defined in modules: math.sqrt(), random.randint(), statistics.mean().
  3. User-defined: created with def.
▶ Try it YourselfPython
Ctrl + Enter to run

Parameters vs arguments#

  • Parameters (formal) appear in the function header; arguments (actual) are values passed in the call.
  • Default parameters must come after non-default ones: def f(a, b=2) ✓, def f(a=1, b) ✗.
  • A function can return multiple values as a tuple: return mn, mx.
हिंदी में समझें

फ़ंक्शन की परिभाषा में लिखे नाम पैरामीटर (औपचारिक) कहलाते हैं और कॉल करते समय दिए गए मान आर्ग्युमेंट (वास्तविक)। डिफ़ॉल्ट पैरामीटर हमेशा बाकी पैरामीटरों के बाद लिखे जाते हैं।

Scope of variables#

  • Local: created inside a function - exists only there.
  • Global: created outside all functions. To change a global inside a function, declare global x.
▶ Try it YourselfPython
Ctrl + Enter to run

Mutable arguments#

Lists passed to a function can be changed inside it (the function receives a reference); integers and strings cannot.

▶ Try it YourselfPython
Ctrl + Enter to run

Exam tips#

  • Output questions on scope and default arguments are very common - trace line by line.
  • A function without return returns None.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Max and min from a function

Write a function min_max(L) that returns the smallest and largest numbers of list L (in that order). Do not use built-in min()/max().

Expected output:
(1, 9)

Quick Quiz

Q1.

A function with no return statement returns

Q2.

Which header is invalid?

Q3.

To modify a global variable inside a function use

Q4.

Values passed in a function call are

Q5.

return a, b returns a