LimioLearn in Flow
🏆 Đấu trường
Đăng nhậpĐăng ký
← Programming for Data Science

Bạn đang xem thử công khai

Đăng nhập để lưu tiến độ, làm bài tập, thảo luận và nhận phản hồi.

Đăng nhập
Module 1: Fundamentals of Python Programming

Functions

In / Lưu PDF

Functions

Review lesson. A summary of the functions part of Module 1, for quick reference and self-checking after unit 1.9.

Syntax and parameters

def area(width, height=1, *extras, **options):
    return width * height
ConceptMeaning
ParameterA name in the function definition (width, height)
ArgumentA value passed at call time (area(3, 4))
Default parameterheight=1 — used when no argument is passed
*argsCollects extra positional arguments into a tuple
**kwargsCollects keyword arguments into a dict
return a, bReturns multiple values (actually a tuple)
lambda x: x ** 2A one-line anonymous function, often used as key= for sorted

Variable scope

  • Assigning inside a function creates a new local variable and does not change a variable with the same name outside.
  • To change an outer variable, you must declare global x inside the function (use sparingly; prefer passing values in and using return).

Remember

  • A function should do one thing and have a name that says what it does.
  • Place parameters that have default values after the required parameters.