✅ Python Variable Naming Rules & Guidelines (20 Total)🧩 Basic Rules (Syntax Requirements):
- Must begin with a letter (a–z, A–Z) or an underscore
_.
–my_var,_value✅ - Cannot begin with a digit.
–1value❌ (Invalid) - Can include letters, digits, and underscores only.
–user1,score_2✅ - Cannot contain spaces.
–user name❌ → Useuser_name✅ - Cannot contain special characters like
@,#,$,%, etc.
–name$❌ - Cannot be a Python keyword.
–class,if,while❌ → Reserved words - Case-sensitive.
–ageandAgeare two different variables. - No punctuation allowed (e.g.,
!,?,.)
–price!❌ - Can be of any length.
– But very long names are discouraged. - Do not use dashes
-
–my-variable❌ → Usemy_variable✅
🧠 Best Practices (Good Naming Habits):
- Use descriptive names.
–total_amountis better thanta. - Use lowercase letters (snake_case) for regular variables.
–user_age✅ - Use all capital letters for constants (by convention).
–MAX_SPEED = 100 - Avoid single-character names (unless for short loops).
– Useindexinstead ofi, unless in a loop. - Do not use names that are similar to built-in functions.
– Avoid naming a variablelist,str,int, etc. - Prefix private/internal-use variables with an underscore
_.
–_internal_value - Avoid using double underscores unless you're defining special methods.
–__init__is used by Python internally. - Use consistent naming style throughout your code.
– Stick tosnake_case, don’t mix withcamelCase. - Avoid acronyms or shorthand unless widely known.
–user_idis better thanuid. - Comment your variables if their purpose isn't obvious.
– Helps improve code readability and maintainability.