Responsive Advertisement

Naming conventions for Python variables

The rules for Pyhton variable naming.

Variables are considered to be identifiers having a physical memory location, which are used to hold values temporarily during the program execution.

Python interpreter can determine on itself that what type of data is stored in the variable, so before assigning a value, variables do not need to be declared.

We use the equal to sign ‘=’ to assign values to a variable. It assigns the values of the right side operand to the left side operand i.e. the variable.

For variables, the Python naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables

  • A variable name must start with an alphabet or an 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 _ ),​and there is no whitespace or special characters are allowed
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • Keywords such as "True", "False" or "if" cannot be used in a variable name.
  • Finally, a variable name should represent the values the variable is holding.
  • 	
        # A variable name with letters and numbers
        1hello = "Hello Python"
        # # An exception is a variable name cannot start with a number
        # # This code will cause an error.
        # 1hello = "Hello Python"
        
    

    If you execute the code above, there will error message occur below.

    Error message, EXAMPLE!

    	
              -------------------------
          "File ipython-input-6-3cb0aca7cfe0, line 2"
          1hello = "Hello Python"
          ^
          SyntaxError: invalid syntax
        
    

    Correct example of variable

    	
        myvar = "John"
        my_var = "John"
        _my_var = "John"
        myVar = "John"
        MYVAR = "John"
        myvar2 = "John"
        
    

    Variable with multi word

    Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable:

    Camel Case

    Each word, except the first, starts with a capital letter:

    	
       MyVarName = "Rak"
        
    

    Post a Comment

    0 Comments