1.Functions: parameters, arguments, return values, scope
CBSE expects: Distinguish built-in, module and user-defined functions; write functions with positional and default parameters; return one or more values; explain flow of execution and local vs global scope.
- PyRun lesson
- Functions Paid plan
- Cheat sheet
- Python Functions and Lambdas (free)
def area(length, breadth=None):
"""Area of a rectangle; a square if breadth is not given."""
if breadth is None:
breadth = length
return length * breadth
def stats(marks):
return max(marks), min(marks), sum(marks) / len(marks) # returns a tuple
count = 0 # global variable
def add_student(name):
global count # needed only to CHANGE a global inside a function
count += 1
print("Added", name, "-> total", count)
print(area(5, 3), area(4)) # positional, then the default
print(area(breadth=2, length=6)) # keyword arguments, any order
hi, lo, avg = stats([88, 72, 95])
print(hi, lo, round(avg, 2))
add_student("Neha")
add_student("Arjun")
print(len("abc"), abs(-4), max(3, 9)) # built-in functions
import math
print(math.gcd(12, 18)) # a function defined in a module15 16
12
95 72 85.0
Added Neha -> total 1
Added Arjun -> total 2
3 4 9
6