Python Functions

Functions group reusable logic behind a name, and Python gives them unusually flexible argument handling.

Defining a function

A function is declared with the def keyword followed by a name and a parameter list.

def greet(name, greeting="Hello"):
    """Return a greeting for the given name."""
    return f"{greeting}, {name}!"

print(greet("Ada"))
print(greet("Ada", greeting="Welcome"))

Argument types

  • Positional arguments are matched by order.
  • Keyword arguments are matched by name.
  • Default arguments supply a fallback value.
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dictionary.
def summarise(*values, **options):
    total = sum(values)
    label = options.get("label", "Total")
    return f"{label}: {total}"

print(summarise(1, 2, 3, label="Score"))

Scope

Names assigned inside a function are local unless declared global or nonlocal. Python resolves names using the LEGB rule: Local, Enclosing, Global, Built-in.

Lambda functions

squares = list(map(lambda x: x * x, range(6)))
print(squares)

Conclusion

Keep functions short, give them one clear responsibility and return values rather than printing them, so they stay testable.

Useful resources

Hand picked references for this topic
Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Python notes →
CSS

CSS Flexbox Layout

Flexbox lays out items along a single axis and distributes space between them, which makes responsive rows and columns simple.

Read more
Java

Introduction to Java

Java is a statically typed, object oriented language that compiles to bytecode and runs on a virtual machine, which is what makes it portable.

Read more

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.