This tutorial unwraps the three most essential building blocks of Python programming – keywords, identifiers, and variables. All of these are part of the Python programming syntax. So, you should know how to use them to write error-free code.
Introduction to Keywords in Python
There are as many as 33 such keywords in Python, each serving a different purpose. Together, they build the vocabulary of the Python language.
They represent the syntax and structure of a Python program. Since all of them are reserved, you can’t use their names for defining variables, classes, or functions.
What are Python Keywords?
Keywords are special words that are reserved and have a specific meaning. Every keyword has a special action associated with it. They exist to help you perform several programming tasks.
Keyword Properties
Python is a case-sensitive language, and its keywords are also case-sensitive. You must be careful while using them in your code. Also, you cannot use them as variables in your programs. Incorrect use of keywords in Python will result in a syntax error.
We’ve just captured here a snapshot of the possible Python keywords.
List of Keywords in Python
As shown earlier, Python has a long list of keywords you can’t remember all at once. However, it is important you know about them and have some idea of the available keywords. We’ll cover each of them in the rest of the tutorials.
Python provides a simple command to list all the available keywords. You need to open a Python shell and run the following command as shown below.
help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass help>
Alternatively, you can use Python’s keyword module, import it straight from the shell, and run the below commands to view the supported keywords.
>>> 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'] >>>
What are Python Identifiers?
Python Identifiers are user-defined names to represent a variable, function, class, module, or any other object. If you assign some name to a programmable entity in Python, then it is nothing but technically called an identifier.
How to Create Identifiers in Python?
Python language lays down some guidelines for programmers to create meaningful identifiers.
1. To form an identifier, use a sequence of letters either in lowercase (a to z)
or uppercase (A to Z)
. However, you can also mix up digits (0 to 9) or an underscore (_) while writing an identifier.
For example – Names like shapeClass, shape_1, and upload_shape_to_db are all valid identifiers.
2. You can’t use digits to begin an identifier name. It’ll lead to a syntax error.
For example – The name, 0Shape is incorrect, but shape1 is a valid identifier.
3. Also, the 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 can also not have special characters [‘.’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’] in their formation. These symbols are forbidden.
>>> @index=0 SyntaxError: invalid syntax >>> isPython?=True SyntaxError: invalid syntax
5. Python doc states you can have an identifier with unlimited length. But it is just a half-truth.
Using a large name (more than 79 chars) would violate the rule set by the PEP-8 standard. It says.
Limit all lines to a maximum of 79 characters.
How to Test If an Identifier is Valid?
You can test whether a Python identifier is valid or not by using the keyword.iskeyword() function. It returns “True” if the keyword is correct or “False” otherwise.
Please refer to the below snippet.
>>> import keyword >>> keyword.iskeyword("techbeamers") False >>> keyword.iskeyword("try") True >>>
Another useful method to check if an identifier is valid or not is by calling the str.isidentifier()
function. But it is only available in Python 3.0 and onwards.
>>> 'techbeamers'.isidentifier() True >>> '1techbeamers'.isidentifier() False >>> 'techbeamers.com'.isidentifier() False >>> 'techbemaers_com'.isidentifier() True
Dos and Don’ts
Here are some simple suggestions you can note down for using identifiers efficiently in Python.
- Always start a class name with a capital letter. All other identifiers should begin with a lowercase letter.
- Declare private identifiers with the (‘_’) underscore as the first letter.
- Don’t use ‘_’ as a leading and trailing character in an identifier. As Python built-in types already use this notation.
- Avoid using names with only one character. Instead, make meaningful names.
- For example – While i = 1 is valid, writing iter = 1 or index = 1 would make more sense.
- You can use an underscore to combine multiple words to form a sensible name.
- For example – count_no_of_letters.
What are Variables in Python?
A variable in Python represents an entity whose value can change as and when required. Conceptually, it is a memory location that holds the actual value. And we can retrieve the value from our code by querying the entity.
However, it requires assigning a label to that memory location so that we can reference it. And we call it a variable in programming terms.
Related Topic – Is Python Pass by Reference or Value?
How to Create a Variable in Python?
Here are some simple steps to create a variable in Python. It will also be good to understand how Python instantiates a variable for programmers to use them efficiently.
1. Variables don’t require declaration. However, you must initialize them before use. Check this example.
test = 10
Based on the values, Python decides the type of the variable. For example, it assigns an integer type for a numeric value and a string for the text value enclosed in quotes.
2. The above expression will lead to the following actions.
- Python will create an object of type integer.
- The name “test” will be assigned to the newly created object.
- Python will initialize the variable with a value of 10.
The variable ‘test’ will act as a reference to value ’10’. Please refer to the illustration shown below.
Example.
| ~~~~~ | ----- ~~~~~~~~~ ------- **** ( test ) ----- Reference ------- ** 10 ** | ~~~~~ | ----- ~~~~~~~~~ ------- **** Variable ----- ~~~~~~~~~~ ------- Object
How Python Instantiates a Variable?
1. Whenever the expression changes, Python associates a new object (a chunk of memory) to the variable for referencing that value. And the old one goes to the garbage collector.
Let’s check with the help of an example.
>>> test = 10 >>> id(test) 1716585200 >>> test = 11 >>> id(test) 1716585232 >>>
2. Also, for optimization, Python builds a cache and reuses a few immutable objects, such as small integers and strings.
3. An object is just a region of memory that can hold the following.
- The actual object values.
- A type designator to reflect the object type.
- The reference counter determines when it’s OK to reclaim the object.
4. It’s the object which has a type, not the variable. However, a variable can hold objects of different types as and when required.
Check the following example to understand it better.
>>> test = 10 >>> type(test) <class 'int'> >>> test = 'techbeamers' >>> type(test) <class 'str'> >>> test = {'Python', 'C', 'C++'} >>> type(test) <class 'set'> >>>
Difference Between Identifiers and Variables
An identifier is not the same thing as a variable. They have 1 to 1 relationship but are different than each other. Let’s look at their differences.
- Identifiers act as labels for variables, functions, and classes. We can call them names in programming terms. They follow certain rules:
- They can include (a-z, A-Z), digits (0-9), and (_).
- They should not start with a number.
- They cannot use the same name as a keyword in Python.
- They are case-sensitive.
- A variable is a specific memory area to store data. An identifier is a name assigned to the variable. When you create a variable, you link an identifier to a value or object. For example:
code = 10
Here,code
is an identifier. It refers to a variable that stores the integer value10
.
In summary, all variables are identifiers, but not all identifiers are variables.
Before You Leave
Congratulations on completing this tutorial. Now, you have a fair idea of how keywords, identifiers & variables work in Python. Python has several important programming terms which you you will learn gradually.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Facebook) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.