
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Allowed Characters in Python Function Names
In Python, function names follow specific rules. A valid function name can only contain certain characters, and it must follow the naming conventions defined in the Python language syntax.
Using the correct characters ensures that your code runs without syntax errors and stays readable.
Allowed Characters in Function Names
Python function names can consist of the following characters -
- Letters (A-Z, a-z)
- Digits (0-9) ? but not at the beginning
- Underscores (_) ? often used to separate words
Function names must follow these rules -
- Must start with a letter or underscore
- Cannot start with a digit
- Cannot use special characters like !, @, #, $, %, -, +, /, *, etc.
- Cannot be the same as Python keywords (like def, if, class, etc.)
Example of Valid Function Names
Following is the example of some valid function names that follow the above rules -
def calculate_total(): return 100 def _helper(): return "I'm private" def convertToInt(value): return int(value) def sum2025(): return 2 + 0 + 2 + 5 # Make it executable if __name__ == "__main__": print("Total:", calculate_total()) print("Helper message:", _helper()) print("Converted to int:", convertToInt("42")) print("Sum of 2025 digits:", sum2025())
These function names are valid and will run without errors -
Total: 100 Helper message: I'm private Converted to int: 42 Sum of 2025 digits: 9
Example of Invalid Function Names
The function names in the following example are invalid and will raise a SyntaxError -
def 2calculate(): # Starts with a number return 0 def total-cost(): # Uses hyphen return 0 def print!(): # Uses special character return 0 def def(): # Uses a Python keyword return 0
Following is the errror obtained -
SyntaxError: invalid syntax
Python does not allow digits at the start or special characters in names. Also, def is a reserved word, so it cannot be used as a function name.
Naming Functions: Do's and Don'ts
Here are some good tips for naming your functions -
- Use lowercase letters with underscores to separate words ? this follows Python's naming convention (e.g., calculate_total_price).
- Make names descriptive so that someone reading your code can easily tell what the function does (e.g., send_email_to_user is clearer than send).
- Avoid one-letter names for functions unless absolutely necessary (such as in small lambda functions).
- Do not use names of built-in functions like list, str, sum, etc., to avoid overwriting or causing confusion with Python's built-in behavior.
Advertisements