An article on understanding Python keywords, identifiers, and variables

Time:2021-12-4
catalogue
  • preface
  • 1、 Python keyword
  • 2、 Python identifier
    • 2.1 guidelines for creating identifiers in Python
    • 2.2 test whether the identifier is valid
    • 2.3 best practices for identifier naming
  • 3、 Python variables
    • summary

      preface

      The purpose of this quick tutorial is to teach you about Python keywords, identifiers, and variables. These are the basic building blocks of Python programming. Therefore, you must know everything about them.

      The python keyword is a unique programming term designed to perform certain operations. There are up to 35 such keywords in Python, each with a different purpose. Together they built a vocabulary for the python language.

      They represent the syntax and structure of Python programs. Because they are reserved, you cannot use their names to define variables, classes, or functions.

      1、 Python keyword

      A keyword is a special word that is reserved and has a specific meaning. Python has a set of keywords that cannot be used as variables in programs.

      All keywords in Python are case sensitive. Therefore, you must be careful when using them in your code. We just captured a snapshot of possible Python keywords here.

      Displaying Python keywords using Python shell

      This is a long list that needs to be remembered at one time. We mention it here only to give you a preliminary understanding of the available keywords. However, we will cover each of them in the remaining tutorials. You don’t have to rush to remember them, but try to learn to use them step by step.

      Another thing you should note is that the list above may change. The language can get rid of some old keywords and introduce new keywords in future versions.
      Therefore, to get the latest list, you can open the python shell and run the following command, as shown in the following code snippet.

      
      >>> import keyword
      >>> keyword.kwlist
      ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
      >>>
      

      2、 Python identifier

      A python identifier is a user-defined name that represents a variable, function, class, module, or any other object. If you assign some names to a programmable entity in Python, it is technically just called an identifier.

      The python language makes a set of rules for programmers to create meaningful identifiers.

      2.1 guidelines for creating identifiers in Python

      1. In order to form an identifier, any lowercase (a to Z) or uppercase (a to Z) of the letter sequence used. However, you can also confuse numbers (0 to 9) or underscores () when writing identifiers.

      For example, the name of – like shapeclass,   shape_ 1 and upload_ shape_ to_ DB is a valid identifier.

      2. You cannot use a number as the beginning of an identifier name. It can cause syntax errors.

      For example – the name 0shape is incorrect, but shape1 is a valid identifier.

      3. In addition, keywords are reserved, so you should not use them as identifiers.

      
      >>> for=1
      SyntaxError: invalid syntax
      >>> True=1
      SyntaxError: can't assign to keyword
      

      4. Python identifiers cannot have special characters [‘.’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’]. These symbols are prohibited.

      
      >>> @index=0
      SyntaxError: invalid syntax
      >>> isPython?=True
      SyntaxError: invalid syntax
      

      5. The python document says you can have an identifier of unlimited length. But it’s only half true.

      Using a large name (more than 79 characters) will result in a violation of the rules set by the pep-8 standard. It will prompt

      
      Limit all lines to a maximum of 79 characters.

      2.2 test whether the identifier is valid

      You can use the keyword. IsKeyword () function to test whether the python identifier is valid. If the keyword is correct, return “true”, otherwise return “false”.

      Please refer to the following clip.

      
      >>> import keyword
      >>> keyword.iskeyword("techbeamers")
      False
      >>> keyword.iskeyword("try")
      True
      >>>

      Another useful way to check whether an identifier is valid is to call the str.isidentifier () function. However, it is only available in Python 3.0 and later.

      
      >>> 'techbeamers'.isidentifier()
      True
      >>> '1techbeamers'.isidentifier()
      False
      >>> 'techbeamers.com'.isidentifier()
      False
      >>> 'techbemaers_com'.isidentifier()
      True

      2.3 best practices for identifier naming

      • It’s best to start the class name with a capital letter. All other identifiers should begin with a lowercase letter.
      • Use the (” ‘) underscore as the initial to declare a private identifier.
      • Do not use ” as leading and trailing characters in identifiers. Because Python built-in types already use this notation.
      • Avoid using names with only one character. Instead, take meaningful names.

      For example — although I = 1 is valid, it makes more sense to write ITER = 1 or index = 1.

      • You can use underscores to combine multiple words into a reasonable name.

      For example – count_ no_ of_ letters。

      3、 Python variables

      Variables in Python represent an entity whose value can be changed as needed. Conceptually, it is a memory location that holds actual values. We can retrieve values from our code by querying entities.

      But it needs to assign a label to the memory location so that we can reference it. We call it a variable in programming terminology.

      Here are some key facts about Python variables. These will help programmers use them effectively.

      1. Variables do not need to be declared. However, you must initialize it before using it.

      For example-

      
      test = 10
      

      2. The above expression will cause the following actions.

      Create an object to represent the value 10.

      If the variable (test) does not exist, it will be created.

      Associate a variable with an object so that it can reference a value.

      The variable ‘test’ is a reference to the value ’10’. Please refer to the figure below.

      For example-

      
      | ~~~~~ | ----- ~~~~~~~~~ -------   ****
      ( test  ) ----- Reference ------- ** 10 **
      | ~~~~~ | ----- ~~~~~~~~~ -------   ****
       Variable ----- ~~~~~~~~~~ -------  Object
      

      3. Whenever the expression changes, python associates a new object (a piece of memory) with the variable that references the value. The old one goes to the garbage collector.

      For example-

      
      >>> test = 10
      >>> id(test)
      1716585200
      >>> test = 11
      >>> id(test)
      1716585232
      >>>

      4. In addition, for optimization, python builds a cache and reuses some immutable objects, such as small integers and strings.

      5. An object is just a memory area that can hold the following contents.

      Actual object value.

      Type indicator that reflects the type of object.

      Determines when reference counters for objects can be reclaimed.

      6. Objects, not variables, have types. However, variables can hold different types of objects as needed.

      For example-

      
      >>> test = 10
      >>> type(test)
      <class 'int'>
      >>> test = 'techbeamers'
      >>> type(test)
      <class 'str'>
      >>> test = {'Python', 'C', 'C++'}
      >>> type(test)
      <class 'set'>
      >>>
      

      summary

      This is the end of this article on Python keywords, identifiers and variables. For more information about Python keywords, identifiers and variables, please search for previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!