Python Functions
A function is a named block of code that runs only when you call it.
Creating and Calling a Function
Use the def keyword, a name, brackets and a colon. The body is indented.
Example
def greet():
print("Assalam o Alaikum!")
print("Welcome to Workownix")
greet()
greet()Assalam o Alaikum! Welcome to Workownix Assalam o Alaikum! Welcome to Workownix
Write the code once, use it many times.
Parameters and Arguments
A function can receive values. The names in the brackets are parameters. The values you pass when calling are arguments.
Example
def greet(name, city):
print(f"Hello {name} from {city}")
greet("Ayesha", "Karachi")
greet("Usman", "Multan")Hello Ayesha from Karachi Hello Usman from Multan
Returning a Value
return sends a result back to the caller. The function stops at return.
Example
def total_bill(price, qty):
return price * qty
bill = total_bill(250, 4)
print(bill)
print(total_bill(99, 2) + 50)1000 248
A function without return gives back None.
Default Values and Keyword Arguments
Example
def make_tea(sugar=2, milk="full"):
return f"Tea with {sugar} sugar and {milk} milk"
print(make_tea())
print(make_tea(1))
print(make_tea(milk="less", sugar=0))Tea with 2 sugar and full milk Tea with 1 sugar and full milk Tea with 0 sugar and less milk
With keyword arguments (milk="less"), the order does not matter.
Any Number of Arguments
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
Example
def add_all(*numbers):
return sum(numbers)
def profile(**info):
for key, value in info.items():
print(key, "=", value)
print(add_all(5, 10, 15, 20))
profile(name="Sara", age=21)50 name = Sara age = 21
Docstrings
A string on the first line of a function explains what it does. Tools and editors show it as help.
Example
def area(length, width):
"""Return the area of a rectangle."""
return length * width
print(area(12, 8))96
Scope
Variables created inside a function are local. They exist only inside that function.
Example
def show():
message = "inside"
print(message)
show()
print(message)inside NameError: name 'message' is not defined
Keep functions small and give each one a single job. Pass values in with parameters and send results out with return, instead of relying on outside variables.
Lambda Functions
A lambda is a tiny function written in one line, often used with sorted(), map() or filter():
Example
square = lambda x: x * x
print(square(6))
students = [("Ali", 72), ("Sana", 91), ("Omar", 85)]
print(sorted(students, key=lambda s: s[1], reverse=True))36
[('Sana', 91), ('Omar', 85), ('Ali', 72)]Exercise
Exercise
What does a Python function return if it has no return statement?
