Concepts / Writing Your First Function

Writing Your First Function

The def keyword marks the start of a function definition and is required for every function.

  • Programming

The First Marker

A function definition needs a clear starting marker. In Python, that marker is the reserved keyword def. When Python sees def, it expects the definition to continue with a function name, parentheses for parameters, a colon, and the function body. Learning to recognize this structure is the first step in writing a function.

Reading a Definition

A function definition is organized around def. After def comes the function name, followed by parentheses, a colon, and the function body. The name is an identifier, so it must follow the same naming rules as a variable. The parentheses provide the place for parameters, and the colon marks the point after which the function body begins.

defstarts the definitionfunction_nameidentifier(parameters begin)parameters end:body beginsfunction bodyinstructionsfollowed byfollowed bypaired withfollowed byintroduces
What does def mark, and how is a function definition arranged around it?
python

In this generated example, def marks the beginning, greet_user is the function name, the empty parentheses show the parameter position, and the colon introduces the body. The example uses snake_case, the naming convention Python strongly favors for function names.

Choosing a Valid Name

Function names follow exactly the same rules as variable names. A valid name starts with a letter or an underscore. After that first character, it may contain letters, numbers, and underscores. It cannot be a Python keyword. These are naming constraints, not merely style preferences.

calculate_totalletters and underscore2usersnumber at startuser2number not at startuser-nameinvalid character_helperstarts with underscoreifPython keyword
Which parts of a proposed function name are allowed, and why do some names fail?
RuleGenerated exampleReason
Start with a letter or underscorecalculate_totalThe first character is a letter
Numbers may appear after the first characteruser2The number is not at the beginning
Use only letters, numbers, and underscoresuser_nameThe name uses letters and an underscore
Do not use a Python keywordifif is reserved by Python

Function names use the same identifier rules as variable names.

Best practice

Python allows both snake_case and camelCase under its naming rules, but Python convention strongly favors snake_case for function names. Names such as calculate_total and send_message follow that convention and are easier to read consistently with other Python code.

Avoiding Name Collisions

A function name and a variable name should not be reused in the same scope. If a function is given a name and that same name is later assigned to a variable, the variable assignment overwrites the function. The function then becomes inaccessible through that name. This can produce confusing behavior because the code may still look as though the function exists.

greetfunction namegreetvariable valuevariable assignment overwrites
What happens when the same name is first used for a function and then assigned to a variable?
Before
def greet():
    pass

greet names a function

After
def greet():
    pass

greet = 5

greet names a variable value, so the function is inaccessible through greet

Mistakes to Catch Early

  • Common mistake

    Treating function names as if they had different rules from variable names

    What it looks like

    Using a function name that would not be valid as a variable name

    Why it fails

    Function names and variable names follow the same naming constraints.

    Do this instead

    Check that the name starts with a letter or underscore, uses only letters, numbers, and underscores, and is not a Python keyword.

  • Common mistake

    Starting a function name with a number

    What it looks like
    def 2users():
    Why it fails

    A valid function name cannot begin with a number.

    Do this instead

    Place the number later in the name or choose a name such as users2.

  • Common mistake

    Using a space, hyphen, or other invalid character in a function name

    What it looks like
    def send-message():
    Why it fails

    Function names may contain only letters, numbers, and underscores.

    Do this instead
    Use underscores, as in send_message.
  • Common mistake

    Using a Python keyword as a function name

    What it looks like
    def class():
    Why it fails

    Keywords are reserved for Python syntax and cannot be used as function or variable names.

    Do this instead

    Choose a different available identifier.

  • Common mistake

    Reusing a function name for a variable in the same scope

    What it looks like
    def greet():
        pass
    
    greet = 5
    Why it fails

    The variable assignment overwrites the function, making it inaccessible through that name.

    Do this instead

    Give the variable and function different names.

  • Common mistake

    Using camelCase when the project follows Python convention

    What it looks like

    calculateTotal

    Why it fails

    The name may satisfy Python's naming rules, but Python convention strongly favors snake_case for function names.

    Do this instead

    Prefer calculate_total for consistent, readable Python code.

Name Check Practice

EASY

For each proposed function name, decide whether it follows Python's naming rules. If it is invalid, identify the rule it breaks. If it is valid but not written in the preferred convention, rewrite it in snake_case: calculate_total, 3items, send-message, class, user_count, calculateTotal.

Hints
  • Check the first character before checking the rest of the name.
  • Look for characters other than letters, numbers, and underscores.
  • Remember that Python keywords cannot be used as names.
  • A valid camelCase name can still be rewritten to the preferred snake_case convention.
Worked example

Checking a Proposed Function Name

Evaluate the generated name calculateTotal.

  1. 1
    Check the first character

    The name begins with a letter, so it passes the first-character rule.

  2. 2
    Check the remaining characters

    The name contains letters only, so it passes the allowed-character rule.

  3. 3
    Check for a keyword

    The proposed name is not the Python keyword def or another reserved keyword such as if, for, or class.

  4. 4
    Apply the convention

    The name is valid under Python's naming rules, but Python convention favors snake_case for function names.

Result

calculateTotal is a valid function name, but calculate_total is the preferred conventional form.

Key Takeaways

  1. 1
    Every Python function definition begins with the def keyword.
  2. 2
    Function names follow the same rules as variable names: start with a letter or underscore, use only letters, numbers, and underscores, and avoid Python keywords.
  3. 3
    Python convention strongly favors snake_case for function names, even though camelCase can satisfy the basic naming rules.
  4. 4
    Do not use the same name for a function and a variable in the same scope because the variable assignment overwrites the function.
  5. 5
    Good function naming prevents syntax problems, confusing code, and accidental loss of access to a function.

At a glance

  • def marks the start of every function definition.
  • Function names use exactly the same naming rules as variable names.
  • Names cannot begin with numbers, contain invalid characters, or be Python keywords.
  • snake_case is the preferred Python convention for function names.
  • Using the same name for a function and a variable in the same scope causes the variable assignment to overwrite the function.

Related concepts

More concepts starting with W