Variable Names

Introduction:

  • Variables can have short names like x or y, or more descriptive names like age, carname, or total_volume. Understanding the rules for naming variables is essential for writing clear and error-free code.

Rules for Variable Names:

  1. A variable name must start with a letter or the underscore character.
  2. A variable name cannot start with a number.
  3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  4. Variable names are case-sensitive (e.g., age, Age, and AGE are three different variables).
  5. 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:
  1. Camel Case:
    • Each word, except the first, starts with a capital letter.
    • Example: myVariableName = "John"
  2. Pascal Case:
    • Each word starts with a capital letter.
    • Example: MyVariableName = "John"
  3. Snake Case:
    • Each word is separated by an underscore character.
    • Example: my_variable_name = "John"

Exercises:

  1. 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
  2. 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