Variable Names
Introduction:
- Variables can have short names like
xory, or more descriptive names likeage,carname, ortotal_volume. Understanding the rules for naming variables is essential for writing clear and error-free code.
Rules for Variable Names:
- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- Variable names are case-sensitive (e.g.,
age,Age, andAGEare three different variables). - A variable name cannot be any of the Python keywords.
Examples of Legal Variable Names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Examples of Illegal Variable Names:
2myvar = "John" # Starts with a number
my-var = "John" # Contains a hyphen
my var = "John" # Contains a space
Note:
- Variable names are case-sensitive.
Multi-Word Variable Names:
- Variable names with more than one word can be made more readable using different conventions:
- Camel Case:
- Each word, except the first, starts with a capital letter.
- Example:
myVariableName = "John"
- Pascal Case:
- Each word starts with a capital letter.
- Example:
MyVariableName = "John"
- Snake Case:
- Each word is separated by an underscore character.
- Example:
my_variable_name = "John"
Exercises:
- Create Variables with Legal Names:
Write code to create variables using legal names.
username = "Alice" user_age = 15 userHeight = 5.6 print(username, user_age) print(userHeight)- Output:
Alice 15 5.6
- Output:
- Identify Illegal Variable Names:
Identify which of the following are illegal variable names and explain why:
1st_name = "John" last-name = "Doe" Full Name = "Jane Doe" _address = "123 Main St"
Summary:
- In this tutorial, we learned the rules for naming variables in Python and how to make multi-word variable names more readable using different conventions. Proper variable naming is crucial for writing clear and maintainable code. Practice these rules to become proficient in naming variables in Python