Technical Roadmap

How to name a variable in python

Let's learn the rules for naming a variable before we move on to the next step. We use an identifier to name a variable in Python.

What is an Identifier?

In Python, an Identifier is a name used to identify a variable, function, class, module, or other object. Identifier is the specific name you give to a variable. You can use this name to access that variable.

    The Logicoria Tip    

identifier is like the name of a website on the Internet. Two sites cannot use the same name.

Rules for naming a variable

In Python we have some rules to name a variable. if you break these rules, Python will throw a SyntaxError and your code won't run at all:

       
  • Character Set: You can only use letters (a-z, A-Z), digits (0-9), and underscores (_).
  •    
  • No number at start: An identifier cannot start with a digit. user1 is fine, but 1user is illegal.
  •    
  • Never use Keywords You cannot use Python's 35+ reserved keywords (like True, False, None, and, as, break, etc.) as names.
  •    
  • No Special Characters: You cannot use @, $, %, or ! anywhere in the name.

The Style Rules (PEP 8)

Python has an official style guide called PEP 8. These aren't "laws" that break your code, but following them makes you a better developer:

       
  •         Snake Case: For variables and functions, use lowercase words separated by underscores.                     Example: student_registration_number            
  •    
  •         Camel Case / Pascal Case: Usually reserved for Classes (which you will learn later in the semester).                     Example: StudentProfile            
  •    
  •         Constants: If a value never changes (like PI), use all capital letters.                     Example: MAX_CONNECTION_LIMIT = 100            

Naming Comparisons

                                                                                                                                                                               
Good PracticeBad Practice
user_age = 20 (Descriptive)a = 20 (Vague)
is_logged_in = True (Clear intent)var = True (Meaningless)
total_price = 50.5 (Snake case)Totalprice = 50.5 (Messy casing)

Interview/Exam Tip

         
  • Private Variables: In Python, starting a name with a single underscore (e.g., _internal) is a hint to other coders that the variable is "private" and shouldn't be touched from outside.
  •    
  • Dunder Names: Names that start and end with double underscores (e.g., init) are called "Dunder" (Double Under) methods. These have special magic powers in Python!