What are identifiers ?

Identifiers are a fundamental and extremely important concept in the Python programming language. Simply put, identifiers are used to give a unique name to various elements within a program, such as variables, functions, classes, modules, or other objects. Just as a person in society is identified by their name, similarly, any data or block in Python code is identified by its identifier.

Rules for Creating Identifiers

While naming any variable, function or class in Python, we must follow certain rules. If we ignore these rules, a SyntaxError occurs in the program. These main rules are as follows:
1. Starting : Identifiers Names are never declared with digits. For example = > 8number = 90 Python Interpreter gives error on declaring Identifiers Names with digits.
2. underscore(_) : Space is not used between Identifiers Names while declaring Identifiers Names. In Python underscore (_) is used in place of space in Identifiers Names, for example = > numbere_r = 90
3. case-sensitive : Since Python is a case sensitive language, Identifiers Names are case - sensitive, that is , Number, NUMBER, number are all three different Identifiers Names. These three variables have no relation with each other.
4. Keywords :Python language already stores such words whose meaning is already reserved for Python, hence Identifier Names cannot be given Keyword Names like => print = 90
5. Special Symbols :Special Symbols are never used in Identifier Names. Special symbols like : #, @, $ etc. On using such symbols, Python does not consider the Identifiers valid.

Naming Conventions

Apart from the rules, some global standards are followed to make the code clean and readable :
1. Always choose names that reflect their function. It is better practice to write age = 25 instead of a = 25.
2. Use underscores between words to name variables and functions, e.g. calculate_total_price.
3. The first letter of the name of classes should always be capitalized, e.g. EmployeeDetails.
4. If a name starts with a single underscore (_var), it indicates that it is a 'private' variable. Double underscores (__var) are used for 'strongly private' or name mangling.

roll_number = 101  
def greet():
    print("Hello World !")                                
                            

1. roll_number : This is the identifier of a variable. It follows the rules because it starts with a letter and uses an underscore (_) to separate words.
2. greet : This is the identifier of a function. Whenever we need to call this function, we will use this name.
This small example proves that any name we define ourselves in the code is the identifier.


What are keywords ?

Keywords are an important concept of Python Language which is easy to understand and use. Keywords means that keywords are those words whose meaning and work is already reserved for Python Interpreter. We cannot make any changes in their working style. Just like the work of an aeroplane is to fly in the air. The work of an aeroplane is fixed, it has to fly, similarly the work of keywords is also fixed like: print() function is used to show the result on the screen. We can use print() function

You cannot make any changes to it, you can only use it. There are approximately 35+ keywords in the Python language. You can find out these keywords by running the code given below in Python.

import keyword
print(keyword.kwlist)

Using the above code, we can find out all the keywords available in Python language. Line by line explanation of this code is given below.
1. import keyword : The keyword module file already available in Python language has been imported.
2. print(keyword.kwlist) : This print() function displays the list of all the keywords from the keyword file.

Types Of Keywords

Mainly Keywords in Python Language are divided into the following parts.
1. Importing : Importing Keywords are used in Python to import any module, file, library etc. from, import, as etc. are examples of some importing Keywords.
2. Control Flow Keywords : Control Flow keywords are used to control the programs written in Python language if, else, for, while etc. are Control Flow keywords.
3. Exception Handling Keywords : When we write programs, errors occur almost on running the programs, hence to handle the errors Exception Handling keywords are used try, except, finally etc. are Exception Handling Keywords.
4. Operators Keywords : Logical Operators Keywords are used to write logic in Python Program and, or, not etc. are Logical operators keywords.
5. value keywords : True, False etc. value is keywords.

Key Rules of Python Keywords

1. Not Identifiers : Identifier names can never be placed on keyword names, like = > if = "User" running like this gives an error.
2. Case sensitive : Keyword names are also case-sensitive, like print and PRINT are both different keywords.
3. No Modifications : As already mentioned, the meaning of keywords is already reserved in Python, which means we cannot make any changes in the function of keywords.

Advantages Of Keywords

1. Reserved Meaning : Since the meaning of keywords is already reserved, hence changes cannot be made in the working of keywords.
2. Good performance : Since keywords have been created by the Python team, hence their working is fixed and smooth.
3. Short Program : Since the work of keywords is already reserved, hence we can write a short program using keywords without writing long code.


What are variables ?

Variables are used to store data. A variable is a name in which values ​​are stored. The name of a variable can be understood as a container. Just like any item is stored in a box. Similarly, to store data in computer memory, the data is stored in variables. If we store the data like this in the memory, then it will be very difficult to access that data, but by using the variable in which that data is stored, we can easily work on the data. The data stored in variables can be any text, number or anything. Below some values ​​have been stored in some variables.

a = 15
b = 1.14

a and b are variables which have the values ​​15 and 1.14 stored in them. In Python language = (Operator) is used to store the value inside a variable.

Object Reference / Memory Allocation

The way variables work in Python is completely different from other programming languages ​​(like C, C++, or Java). To understand this, we need to understand the difference between a 'container' and a 'tag'. Let's understand this in depth with very simple words and examples:
In C / C++ / Java : A variable is like a box or container. When you write int x = 10;, a box named 'x' is created in memory and '10' is placed in it.
In Python : A variable is not a box, but a label or tag (Tag/Pointer). When you write x = 10, Python first creates an object named '10' in memory and then binds a string or tag named x to that object.

Let's say we write a few lines of code. Let's see what's happening in Python's memory in the background:

# Case 1: Creating a New Variable
x = 10
# Case 2: Assigning one variable to another
y = x

case 1 : Python created an object in memory with the value 10. Now x points to that 10 object.
case 2: No new 10 object will be created. Instead, a new tag named y will be attached to the old 10 object. This means that both x and y now point to the same object.

Rules for Creating Variable Names

To create variables in Python Programming Language, some rules have to be followed. These rules are given below:
1. There should not be any space in the name of any variable because by giving space the words get divided into parts and Python is not able to know about the correct variable.
2. While creating the names of variables, no spatial symbol (#, space, @, comma) is used in the variable name.
3. Space is not used in the name of variables, but if the name is very long, underscore (_) is used in place of space.
4. Variables are case-sensitive, that is, both a and A are different variable names and they have no relation with each other.


What are constants ?

Constant means such variable in which changes cannot be made. Variables are created in Python and values ​​are stored in variables. We can change the values ​​stored in variables whenever we want, but there are some programs in which we do not want to make changes in the values ​​ stored in variables, hence Constant variables are such variables in which changes cannot be made. Below is a short and simple Python code and its explanation to understand Constant :

GRAVITY = 9.8  
COMPANY_NAME = "TechSol"
print("Company Name :", COMPANY_NAME)
print("Earth Gravity :", GRAVITY)

1. GRAVITY and COMPANY_NAME : GRAVITY and COMPANY_NAME are constants because their names are written entirely in uppercase.
2. Fixed Value : 9.8 and "TechSol" are values ​​that will never change during the entire program's execution.
3. Readability : Any other programmer looking at the code will immediately understand that the values ​​of these variables written in uppercase letters are not to be tampered with or changed anywhere in the code.

Rules for Constants

Since Python does not have a built-in const keyword, its rules are entirely based on naming conventions and best practices :
1. Constant names must always be in uppercase letters.
True: TOTAL_LIMIT = 100 , False: Total_Limit = 100
2. 2. If the name contains more than one word, only underscores (_) should be used to join them.
Example: MAX_LOGIN_ATTEMPTS, DATABASE_PASSWORD
3. Like normal identifiers, constant names can never start with a number. They must always start with a letter or an underscore.
True: PORT_8080 = 8080 , False: 8080_PORT = 8080
4. The use of any special characters (e.g. @, $, %, -) other than the underscore (_) in the name is strictly prohibited.
5. As a rule, all constants should always be written at the top of the script/file or in a separate configuration module, not inside a function or loop.

Features Of Constant

1. Improves Readability : Using PI instead of writing 3.14159 repeatedly in the code makes the code much easier to read and understand.
2. Easy Maintenanc : If a fixed value has to be changed in the future (like tax rate increases from 5% to 18%), then you don't have to change it everywhere in the code. You have to change the value of the constant only at one place.
3. Human Discipline Dependent : It is a unique feature of Python that here constants are completely dependent on the mutual agreement and discipline of the developers, because in the background they work just like normal variables.
4. Global Scope Utility : Constants are usually defined at the top of the program or in a separate file (constants.py), so that they can be easily imported anywhere in the entire project.


Input and Output Functions in Python

Input and Output (I/O) functions play a vital role in Python programming. The fundamental purpose of any computer program is to interact with the user by accepting data, processing it, and returning a meaningful result. In Python, this two-way communication is handled smoothly using the input() and print() functions.
There is a core concept in programming known as GIGO (Garbage In, Garbage Out). This means your output will be accurate only if your input is correct. If the user provides wrong data, the program will inevitably generate an incorrect output.

1. The Output Function: print()

The print() function is the most basic and frequently used built-in function in Python. Its primary purpose is to display text, variables, or the results of calculations on the output window or console screen. It evaluates the expressions you pass to it and converts them into a human-readable string format before displaying them. Example :

print(10)
Code Output
10

In this example, passing the integer 10 inside the print() function directly displays 10 on the screen.

2. The Input Function: input()

The data provided by a user to the program is called input. This data can belong to any data type, such as integers (int), decimal numbers (float), or text (string). Python provides the built-in input() function to capture user data at runtime.Example:

name = input("Enter your name = > ")
Code Output
Enter your name = > shubham

In the statement above, name acts as a variable, which serves as a storage location in the computer's memory. When this line runs, the program pauses and displays the message "Enter your name => ". Once the user types a value (for example, shubham) and presses Enter, the input() function captures that string and stores it safely inside the name variable for later use.

Features Of Input / Output Functions

1. Dynamic Text Prompt : The input() function not only takes input, but also allows displaying a customized message (prompt) (e.g., input("Enter your age: ")). This lets the user know what to type.
2. Default String Input Feature : The most important feature of input() is that whether the user types a number or a letter from the keyboard, it always captures it as a string (String/Text).
3. Automatic Newline Block : The print() function has an in-built feature that automatically moves the cursor to the next line (\n) after completing its task. Its behavior can also be changed with the end parameter.
4. Multi-Object Printing : The print() function can print multiple data types (e.g., string, number, list) simultaneously in a single line separated by a comma (,).


Documentation Strings (Docstrings) in Python

A Documentation String (or Docstring) is a special type of comment used in Python to explain what a specific function, class, module, or method does. Unlike regular comments, docstrings are retained by Python at runtime, making them highly valuable for code maintenance and auto - generation of documentation.

Key Rules for Writing Docstrings

To write clean and Pythonic docstrings, you must follow the official PEP 257 guidelines. If these rules are broken, tools like Sphinx cannot auto-generate your documentation properly.
1. Mandatory Triple Quotes : Always enclose docstrings inside triple double quotes """...""". Never use single quotes # or regular strings '...' or "...".
2. Exact Immediate Placement : Place the docstring on the very first line inside a module, class, or function definition.
3. Imperative Mood Verb : Begin the summary phrase with a commanding verb. Write """Return the total.""" instead of """Returns the total.""" or """Returning the total.""".
4. The Blank Line Gap : For multi-line docstrings, always keep one blank line empty between the first summary line and the rest of the detailed text.
5. Closing Quote Position : In a multi-line docstring, the closing triple quotes """ must sit alone on a completely fresh line.
6. Runtime Accessibility : Do not confuse them with comments. Docstrings are stored in memory and must be readable using the __doc__ attribute or help() function.

Types of Docstrings

Python classifies docstrings into two structural types based on the complexity of the code block they explain.

1. One-line Docstrings

Used strictly for very obvious, simple functions or methods where a single sentence is enough to explain the purpose.
RuleThe opening quotes, the summary text, and the closing quotes must all fit on one single line.

def get_user_id(username):
    """Fetch the unique database ID for a given user."""
    return database.lookup(username)

2. Multi-line Docstrings

Used for complex functions, classes, or modules that accept multiple parameters, raise errors, or return specific data structures.
Rule It starts with a brief one-line summary, followed by a blank line, followed by a deeper explanation of arguments and return types.

def connect_to_server(ip_address, port):
    """Establish a secure network connection to the target server.

    This function initializes a socket connection, performs a handshake 
    protocol, and authenticates the client session with the host.

    Parameters:
    ip_address (str): The valid IPv4 or IPv6 address of the server.
    port (int): The network port number (typically 80 or 443).

    Returns:
    bool: True if connection succeeds, False otherwise.
    """
    return socket.open(ip_address, port)

Docstrings vs. Regular Comments

Feature Regular Comments (#) Docstrings (""")
Purpose Explains how a specific line of code works internally. Explains what a function/class does for someone using it.
Runtime Access Ignored completely by the Python interpreter. Saved in memory and accessible via code or IDEs.
Position Can be placed anywhere in the code. Must be the first statement inside the block.

What are Escape Characters ?

Escape characters are used for good programming in Python and to keep large programs clean. Escape characters are used when we need to write such symbols in a string which are normally interpreted differently by Python. Escape characters in Python start with a backslash (\). Some important escape characters used in Python language are given below.

1. \n : Newline Character : \n (Backslash n) is used to break a line in the middle of a string. As soon as the compiler reads \n, it moves all the text that follows it to the next line (New Line). It is used to organize the output as a paragraph or list.

print("Hello\nWorld") 
Code Output
Hello
World

print("Hello\nWorld") = > This Print() shows Hello in the first line and World in the second line on the screen.

2. \t : Horizontal Tab : \t (Backslash t) is used to give a large space (which is equal to 4 or 8 normal spaces on keyboard) between two words or values ​​within a string. Its biggest advantage is when we need to arrange the data in table format or in the form of columns at equal distance on the screen.

print("Hello\tWorld") 
Code Output
Hello   World

This print() function displays the words "Hello" and "World" on the screen by giving a space of 1 tab between them.

3. \' : Single Quote : If you have enclosed your entire string in single quotes ('...'), and you want to include another single quote within that string (e.g. Aman's book in English), Python gets confused about the end of the string and throws a SyntaxError. To avoid this error, \ is placed before the inner single quote.

print('It\'s Python')
Code Output
It's Python

print('It\'s Python') This function displays single quotes(') between words.

4. \" : Double Quote : Similar to the rule for \', if your main string is enclosed within double quotes ("..."), and you want to display double quotes inside to highlight a dialogue or a specific word, you need to use \". This tells the compiler that the double quote is not meant to terminate the string, but is just normal text to be printed on the screen.

print("He said \"Hi\"")
Code Output
He said "Hi"

print("He said \"Hi\"") This function displays double quotes(") between words.

5. \b : Backspace : \b (Backslash b) works like the 'Backspace' button on the keyboard. Wherever \b appears in a string, it removes the preceding (leftmost) character or space from the output screen. This is often used for dynamic formatting or to quickly remove unwanted spaces.

print("Hello\bWorld")
Code Output
HellWorld

print("Hello\bWorld") This function shows the entire words by removing the last letter of the first word of both the words.

Features Of Escape Characters

1. Syntax Non-Disruption : They allow developers to include legally restricted characters (like internal double quotes " inside a double-quoted string) without prematurely breaking the string boundaries or causing a SyntaxError.
2. ASCII-Level Translation : They act as non-printable ASCII instructions. When the Python interpreter parses them, it translates the two character symbols (like \ and n) into a single byte payload instruction (like the ASCII LF/Line Feed byte 0x0A).
3. Cross-Platform Output Normalization : Characters like \n abstract away lower-level OS differences. Python intelligently handles whether the underlying host platform expects a Carriage Return and Line Feed (\r\n on Windows) or just a Line Feed (\n on Unix/Linux systems).
4. Universal Type Integrity : Escape sequences are fully embedded inside standard str primitives. They do not alter the data type of the string; they only alter its visual and structural layout upon evaluation or printing.


Indentation In Python

One of the most unique and important features of the Python programming language is its indentation system. While other programming languages, such as C, C++, Java, and JavaScript, use curly brackets { } to indicate where a block of code (such as a loop, function, or conditional statement) begins and ends, Python handles this task entirely with whitespace.

Simply put, indentation refers to the spaces or tabs placed at the beginning of a line of code. In Python, this isn't just for the sake of making the code look pretty, but it's an essential part of the syntax.

How does indentation work ?

Whenever you start a block of code in Python (such as an if statement, a for loop, or a def function), a colon (:) is placed at the end of that statement. All lines immediately following this colon must begin with a space. This space tells the interpreter that these lines are all part of the same block.

if 5 > 2:
    print("5 is actually greater than 2!") # Indentation of 4 spaces
    print("This line is also inside an 'if' block.")

print("This line is outside the 'if' block because its indentation is broken.")

Strict Rules of Indentation

If you are writing code in Python, you must strictly follow these rules :
1. Uniformity Rule : All lines within the same code block must have exactly the same number of spaces. If you give 4 spaces in the first line and 5 spaces in the second, the code will not run.
2. Standard Spaces : As a rule, you can use any number of spaces from 1, but according to Python's official style guide (PEP 8), 4 spaces are considered the most ideal and standard.
3. Tabs vs Spaces : You should use either only 'Tabs' or only 'Spaces' throughout your program. Mixing the two creates confusion in the code and leads to errors.

Some Indentation Errors

A. IndentationError: expected an indented block : This error occurs when you start a block (by using a colon :), but forget to give a space on the next line.

if True:
print("Hello")
Code Output
IndentationError: expected an indented block after 'if' statement on line 1

B. IndentationError: unindent does not match any outer indentation level : This error occurs when you give different amount of spaces inside the same block.

def my_function():
    print("First Line")   print("first line") # 4 spaces
     print("Second Line")   #5 Space (Mistake: Space mismatched!)
Code Output
IndentationError: unindent does not match any outer indentation level

Advantages Of Python Indentation

1. Unmatched Readability : Since every developer has to provide spaces, all Python code always looks neat and organized.
2. Freedom from curly brackets : The absence of { } and semi-colon ; in the code makes the code look much lighter, modern and less clutter-free.
3. Fewer Logical Bugs : In other languages, developers often forget to use the closing bracket }, which makes it difficult to find logical errors. In Python, the block ends automatically as soon as the indentation ends.


Comments In Python

If it comes to simplifying the user's work, then it is comments. After commenting any code or line, the Python interpreter does not execute that code or line. # is used to comment a program/line in the Python language. By adding # before a line , that line becomes a comment. Python supports three primary types of comments based on how they are written and applied :
1. Single-Line Comments : Single-line comments are used for brief, quick explanations of a specific line or expression. They begin with the hash or pound symbol (#). Anything written after the # on that exact line is treated as a comment.

# Initialize the user session counter to zero
session_counter = 0  

2. Inline Comments An inline comment is a single-line comment placed on the exact same line as a code statement, separated by at least two spaces. It is highly effective for explaining specific or tricky calculations on the spot.

final_price = base_price * 1.18  # 1.18 represents 18% GST tax rate

3. Multi-Line Comments : Python does not feature a dedicated built-in syntax symbol for multi-line comments (unlike /* ... */ in C++ or Java). However, developers use two highly accepted methods to write long, multi-line explanations :

Method A: Consecutive Hash Symbols
# This block of code calculates the compounded interest rate
# based on the quarterly financial returns of the user account.
# Ensure the interest rate variable is non-negative.
Method B: Multi-line String Literals (The Workaround)
"""
This is treated as a multi-line comment.
The interpreter will read it but won't execute it
because it is not assigned to any variable.
"""

Key Rules & Best Practices for Writing Comments

Writing too many comments or writing them poorly can ruin your codebase. Follow these industry standards :
1. Avoid the Obvious : Do not write comments that state exactly what the code is doing.
Bad: x = 5 # Assign 5 to x
Good: x = 5 # Maximum allowed login attempts before locking account
2. Keep Them Up to Date : A comment that contradicts the actual running code is worse than no comment at all. Always update your comments when you modify the logic.
3. Code Block Alignment : : Comments must match the exact same indentation level as the code block directly beneath them.
4. The Two-Space Rule for Inline : : Always leave at least two spaces between the end of your code statement and the start of your inline # symbol.

Benefits of comments

1. Readability : Comments are very helpful for understanding a big program, especially for students who start learning coding, comments are very helpful for them.
2. Future : Suppose that you write a 200 lines program and then after a few years, if you see that program, you will not be able to understand some codes/lines of that program. So comments are helpful in understanding a program in the future also.
3. Debugging : After finding an error in the program, it is helpful in separating some part of the program.
4. Explanations : It is helpful in explaining big programs.
5. Different Person : Suppose that if you give your program to another person, then it is helpful in explaining the program to him.