Category: Python Tutorial

  • Python Comments

    In Python, comments are the lines in the source code that the interpreter ignores during the execution of the program. These are programmer-readable explanations or annotations added to the code with the purpose of making it easier for humans to understand. Comments improve the readability of the code, help in debugging, and serve as documentation for future developers.

    Let us see a simple example showing how comments work in Python.

    Example

    # this is a simple comment  
    print("Welcome to Learn Python App to learn Python")  

    Output:

    Welcome to Learn Python App to learn Python

    Explanation:

    In this example, we have added a comment using a hash ‘#’ symbol. We can also see that the Python interpreter has ignored the commented part during the execution of the program.

    Types of Comments in Python

    There are primarily three types of comments used in Python, such as:

    1. Single-line Comments
    2. Multi-line Comments
    3. Docstrings
    Python Comments

    Let us discuss these types with the help of examples:

    1. Python Single-line Comments

    In Python, a single-line comment starts with a hash ‘#’ symbol, and Python will ignore it. The single-line comments are utilized to provide short explanations or notes about the code.

    Let us see a simple example of single-line comments in Python.

    Example

    # example of single-line comment  
       
    # this is a single-line comment  
    print("Welcome to Learn Python App!")  

    Output:

    Welcome to Learn Python App!

    Explanation:

    In the above example, we have added a single-line comment using the hash ‘#’ symbol. As a result, the Python interpreter ignored this line of code and executed the next line of code to print a statement.

    Inline Comments

    An inline comment is a type of single-line comment that appears on the same line as a statement and is used to explain a particular segment of that line.

    Here is an example of inline comments in Python.

    Example

    # example of inline comment  
      
    print("Welcome to Learn Python App!") # this is an inline comment  

    Output:

    Welcome to Learn Python App!

    Explanation:

    In the above example, we have added an inline comment using the hash ‘#’ symbol after the print() function. Python interpreter has ignored the commented segment from the line of code.

    2. Python Multi-line Comments

    Unlike other programming languages like C, C++, and Java, Python does not have a dedicated way of writing multi-line comments.

    However, a similar effect can be achieved using the following ways:

    Multiple Single-Line Comments

    One of the basic ways of adding multi-line comments to the source code is by stacking single-line comments with the help of hash symbols ‘#’ on each line.

    Take a look at the following example to write multi-line comments using multiple hash symbols:

    Example

    # example of multiline comment  
      
    # this is a  
    # multi-line comment  
    # added to the code  
    # by stacking multiple  
    # single line comments  
      
    print("Welcome to Learn Python App!")  

    Output:

    Welcome to Learn Python App!

    Explanation:

    Here, the multiple single line comments are stacked together to make it look like a multi-line comment.

    Using Triple Quoted Strings

    We can simulate multi-line comments in Python, with the help of triple quoted strings (”’ or “””). Even though they are technically multi-line strings, we can use them as comments.

    Here is a simple example showing the way of adding multi-line comments to the code using the triple-quoted strings.

    Example

    # example of multiline comment  
    
      
    
    '''''This is a  
    
    multi-line comment  
    
    added to the code  
    
    using the triple  
    
    quoted string 
    
    '''  
    
      
    
    print("Welcome to Learn Python App!")

    Output:

    Welcome to Learn Python App!

    Explanation:

    Although triple quotes are not technically comments, but in the above example, we have used it as a comment for quick notes or debugging.

    3. Python Docstrings

    Docstrings, short for documentation strings, are special multi-line strings in Python that we can utilized in order to document functions, classes, methods, and modules.

    Unlike regular comments, docstrings are stored at runtime. We can access them using the built-in help() function or the __doc__ attribute. This makes them incredibly helpful in building a well-documented, maintainable code.

    Here’s a quick example to understand the working of docstrings in Python.

    Example

    # example of docstring  
      
    # defining a function  
    def welcome(name):  
      ''''' 
      This function prints a  
      welcome message for the user 
      '''  
      print(f'Hello, {name}!, Welcome to Learn Python App.')  
      
    # calling the function  
    welcome('John')  
      
    # using the __doc__ attribute to access the docstring  
    print("Docstring:", welcome.__doc__)  
    Hello, John!, Welcome to Learn Python App.
    Docstring:
    This function prints a
    welcome message for the user

    Explanation:

    Here, the docstring is stored in the memory during the runtime. And when we called the __doc__ attribute, the stored docstring is returned.

    Best Practices to Write Comments

    The following are some tips one can follow in order to make their comments effective:

    1. The code should be self-explanatory. It is recommended to write comments to explain why something is done a certain way.
    2. Always keep the comments concise, to the point, and easy to scan.
    3. Outdated comments can be misleading and harmful. Therefore, it is a good practice to update or remove comments if any changes are made to the code.
    4. Use proper grammar and capitalization to keep the comments more professional and easier to read.
    5. PEP 8 suggests that inline comments should have at least two spaces before the hash ‘#’ symbol. Therefore, it is recommended to follow the PEP 8 spacing rule.

    Conclusion

    In Python, commenting is a vital skill as it enhances the readability and maintainability of the code. Whether we are writing a simple script or developing a complex application, clear and meaningful comments make the code more professional and easier to understand. In this tutorial, we have learned how to add comments to Python programs. We also discussed the different types of comments we have in Python with the help of various examples.

  • Python Operators

    In Python, Operators are the symbols used to perform a specific operation on different values and variables. These values and variables are considered as the Operands, on which the operator is applied. Operators serve as the foundation upon which logic is constructed in a program in a particular programming language.

    Types of Python Operators

    Different types of Operators used in Python are as follows:

    1. Arithmetic Operators
    2. Comparison Operators
    3. Assignment Operators
    4. Logical Operators
    5. Bitwise Operators
    6. Membership Operators
    7. Identity Operators

    Let us now discuss these operators used in Python in the following sections.

    Python Operators

    1. Arithmetic Operators

    Python Arithmetic Operators are used on two operands to perform basic mathematical operations like addition, subtraction, multiplication, and division. There are different types of arithmetic operators available in Python, including the ‘+’ operator for addition, ‘-‘ operator for subtraction, ‘*’ for multiplication, ‘/’ for division, ‘%’ for modulus, ‘**’ for exponent, and ‘//’ for floor division.

    Let us consider the following table of arithmetic operators for a detailed explanation.

    S. No.OperatorSyntaxDescription
    1+ (Addition)r = a + bThis operator is used to add two operands. For example, if a = 15, b = 10 => a + b = 15 + 10 = 25
    2– (Subtraction)r = a – bThis operator is used to subtract the second operand from the first operand. If the first operand is less than the second operand, the value results negative. For example, if a = 20, b = 5 => a – b = 20 – 5 = 15
    3/ (divide)r = a / bThis operator returns the quotient after dividing the first operand by the second operand. For example, if a = 15, b = 4 => a / b = 15 / 4 = 3.75
    4* (Multiplication)r = a * bThis operator is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 20 * 4 = 80
    5% (reminder)r = a % bThis operator returns the reminder after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a % b = 20 % 10 = 0
    6** (Exponent)r = a ** bAs this operator calculates the first operand’s power to the second operand, it is an exponent operator. For example, if a = 2, b = 3 => a**b = 2**3 = 2^3 = 2*2*2 = 8
    7// (Floor division)r = a // bThis operator provides the quotient’s floor value, which is obtained by dividing the two operands. For example, if a = 15, b = 4 => a // b = 15 // 4 = 3

    Now we give code examples of arithmetic operators in Python. The code is given below –

    Example

    a = 46    # Initializing the value of a      
    b = 4     # Initializing the value of b      
        
    print("For a =", a, "and b =", b,"\nCalculate the following:")    
        
    # printing different results    
    print('1. Addition of two numbers: a + b =', a + b)      
    print('2. Subtraction of two numbers: a - b =', a - b)      
    print('3. Multiplication of two numbers: a * b =', a * b)      
    print('4. Division of two numbers: a / b =', a / b)      
    print('5. Floor division of two numbers: a // b =',a // b)      
    print('6. Reminder of two numbers: a mod b =', a % b)      
    print('7. Exponent of two numbers: a ^ b =',a ** b)    

    Output:

    For a = 46 and b = 4
    Calculate the following:
    1. Addition of two numbers: a + b = 50
    2. Subtraction of two numbers: a - b = 42
    3. Multiplication of two numbers: a * b = 184
    4. Division of two numbers: a / b = 11.5
    5. Floor division of two numbers: a // b = 11
    6. Reminder of two numbers: a mod b = 2
    7. Exponent of two numbers: a ^ b = 4477456
    

    2. Comparison Operators

    Python Comparison operators are mainly used for the purpose of comparing two values or variables (operands) and returning a Boolean value as either True or False accordingly. There are various types of comparison operators available in Python, including the ‘==’, ‘!=’, ‘<=’, ‘>=’, ‘<‘, and ‘>’.

    Let us consider the following table of comparison operators for a detailed explanation.

    S. No.OperatorSyntaxDescription
    1==a == bEqual to: If the value of two operands is equal, then the condition becomes true.
    2!=a != bNot Equal to: If the value of two operands is not equal, then the condition becomes true.
    3<=a <= bLess than or Equal to: The condition is met if the first operand is smaller than or equal to the second operand.
    4>=a >= bGreater than or Equal to: The condition is met if the first operand is greater than or equal to the second operand.
    5>a > bGreater than: If the first operand is greater than the second operand, then the condition becomes true.
    6<a < bLess than: If the first operand is less than the second operand, then the condition becomes true.

    Example

    a = 46    # Initializing the value of a      
    b = 4     # Initializing the value of b      
        
    print("For a =", a, "and b =", b,"\nCheck the following:")    
        
    # printing different results    
    print('1. Two numbers are equal or not:', a == b)      
    print('2. Two numbers are not equal or not:', a != b)      
    print('3. a is less than or equal to b:', a <= b)      
    print('4. a is greater than or equal to b:', a >= b)      
    print('5. a is greater than b:', a > b)      
    print('6. a is less than b:', a < b)     

    Output:

    For a = 46 and b = 4
    Check the following:
    1. Two numbers are equal or not: False
    2. Two numbers are not equal or not: True
    3. a is less than or equal to b: False
    4. a is greater than or equal to b: True
    5. a is greater than b: True
    6. a is less than b: False
    

    3. Assignment Operators

    Using the assignment operators, the right expression’s value is assigned to the left operand. Python offers different assignment operators to assign values to a variable. These assignment operators include ‘=’, ‘+=’, ‘-=’, ‘*=’, ‘/=’, ‘%=’, ‘//=’, ‘**=’, ‘&=’, ‘|=’, ‘^=’, ‘>>=’, and ‘<<=’.

    Let us consider the following table of some commonly used assignment operators for a detailed explanation.

    S. No.OperatorSyntaxDescription
    1=a = b + cThis operator assigns the value of the right expression to the left operand.
    2+=a += b => a = a + bAdd AND: This operator adds the operand on the right side to the operand on the left side and assigns the resultant value to the left operand. For example, if a = 15, b = 20 => a += b will be equal to a = a + b and therefore, a = 15 + 20 => a = 35
    3-=a -= b => a = a – bSubtract AND: This operator subtracts the operand on the right side from the operand on the left side and assigns the resultant value to the left operand. For example, if a = 47, b = 32 => a -= b will be equal to a = a – b and therefore, a = 47 – 32 => a = 15
    4*=a *= b => a = a * bMultiply AND: This operator multiplies the operand on the right side with the operand on the left side and assigns the resultant value to the left operand. For example, if a = 12, b = 4 => a *= b will be equal to a = a * b and therefore, a = 12 * 4 => a = 48
    5/=a /= b => a = a / bDivide AND: This operator divides the operand on the left side with the operand on the right side and assign the resultant value to the left operand. For example, if a = 15, b = 2 => a /= b will be equal to a = a / b and therefore, a = 15 / 2 => a = 7.5
    6%=a %= b => a = a % bModulus AND: This operator calculates the modulus of using the left-side and right-side operands and assigns the resultant value to the left operand. For example, if a = 20, b = 10 => a %= b will be equal to a = a % b and therefore, a = 20 % 10 => a = 0
    7**=a **= b => a = a ** bExponent AND: This operator calculates the exponent value using the operands on both side and assign the resultant value to the left operand. For example, if a = 2, b = 3 => a **= b will be equal to a = a ** b and therefore, a = 2 ** 3 = 8
    8//=a //= b => a = a // bDivide (floor) AND: This operator divides the operand on the left side with the operand on the right side and assign the resultant floor value to the left operand. For example, if a = 15, b = 2 => a //= b will be equal to a = a // b and therefore, a = 15 // 2 => a = 7

    Example

    a = 34         # Initialize the value of a      
    b = 6          # Initialize the value of b      
        
    # printing the different results    
    print('a += b:', a + b)      
    print('a -= b:', a - b)      
    print('a *= b:', a * b)      
    print('a /= b:', a / b)      
    print('a %= b:', a % b)    
    print('a **= b:', a ** b)      
    print('a //= b:', a // b)        

    Output:

    Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below –

    a += b: 40
    a -= b: 28
    a *= b: 204
    a /= b: 5.666666666666667
    a %= b: 4
    a **= b: 1544804416
    a //= b: 5
    

    3. Bitwise Operators

    The two operands’ values are processed bit by bit by the bitwise operators. There are various Bitwise operators used in Python, such as bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift (>>).

    Let us consider the following table of bitwise operators for a detailed explanation.

    S. No.OperatorSyntaxDescription
    1&a & bBitwise AND: 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is copied.
    2|a | bBitwise OR: The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
    3^a ^ bBitwise XOR: If the two bits are different, the outcome bit will be 1, else it will be 0.
    4~~aBitwise NOT: The operand’s bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and vice versa.
    5<<a <<Bitwise Left Shift: The number of bits in the right operand is multiplied by the leftward shift of the value of the left operand.
    6>>a >>Bitwise Right Shift: The left operand is moved right by the number of bits present in the right operand.

    Example

    a = 7          # initializing the value of a      
    b = 8          # initializing the value of b      
        
    # printing different results    
    print('a & b :', a & b)      
    print('a | b :', a | b)      
    print('a ^ b :', a ^ b)      
    print('~a :', ~a)    
    print('a << b :', a << b)      
    print('a >> b :', a >> b)     
    

    Output:

    a & b : 0
    a | b : 15
    a ^ b : 15
    ~a : -8
    a << b : 1792
    a >> b : 0
    

    5. Logical Operators

    The assessment of expressions to make decisions typically uses logical operators. Python offers different types of logical operators, such as and, or, and not. In the case of the logical AND, if the first one is 0, it does not depend upon the second one. In the case of the logical OR, if the first one is 1, it does not depend on the second one.

    Let us consider the following table of the logical operators used in Python for a detailed explanation.

    S. No.OperatorSyntaxDescription
    1anda and bLogical AND: The condition will also be true if the expression is true. If the two expressions a and b are the same, then a and b both must be true.
    2ora or bLogical OR: The condition will be true if one of the phrases is true. If a and b are the two expressions, then either a or b must be true to make the condition true.
    3notnot aLogical NOT: If an expression a is true, then not (a) will be false and vice versa.

    Example

    a = 7          # initializing the value of a    
    # printing different results    
    print("For a = 7, checking whether the following conditions are True or False:")    
    print('\"a > 5 and a < 7\" =>', a > 5 and a < 7)      
    print('\"a > 5 or a < 7\" =>', a > 5 or a < 7)    
    print('\"not (a > 5 and a < 7)\" =>', not(a > 5 and a < 7))      
    

    Output:

    For a = 7, checking whether the following conditions are True or False:
    "a > 5 and a < 7" => False
    "a > 5 or a < 7" => True
    "not (a > 5 and a < 7)" => True
    

    6. Membership Operators

    We can verify the membership of a value inside a Python data structure using the Python membership operators. The result is said to be true if the value or variable is in the sequence (list, tuple, or dictionary); otherwise, it returns false.

    S. No.OperatorDescription
    1inIf the first operand (value or variable) is present in the second operand (sequence), it is evaluated to be true. Sequence can either be a list, tuple, or dictionary
    2not inIf the first operand (value or variable) is not present in the second operand (sequence), the evaluation is true. Sequence can either be a list, tuple, or dictionary

    Example

    # initializing a list    
    myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]    
        
    # initializing x and y with some values    
    x = 31    
    y = 28    
        
    # printing the given list    
    print("Given List:", myList)    
        
    # checking if x is present in the list or not    
    if (x not in myList):    
        print("x =", x,"is NOT present in the given list.")    
    else:    
        print("x =", x,"is present in the given list.")    
        
    # checking if y is present in the list or not    
    if (y in myList):    
        print("y =", y,"is present in the given list.")    
    else:    
        print("y =", y,"is NOT present in the given list.")    
    

    Output:

    Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
    x = 31 is NOT present in the given list.
    y = 28 is present in the given list.
    

    7. Identity Operators

    Python offers two identity operators, is and is not, that are used to check if two values are located in the same part of memory. Two variables that are equal do not imply that they are identical.

    S. No.OperatorDescription
    1isIf the references on both sides point to the same object, it is determined to be true.
    2is notIf the references on both sides do not point at the same object, it is determined to be true.

    Example

    # initializing two variables a and b    
    a = ["Rose", "Lotus"]      
    b = ["Rose", "Lotus"]      
        
    # initializing a variable c and storing the value of a in c    
    c = a      
        
    # printing the different results    
    print("a is c => ", a is c)    
    print("a is not c => ", a is not c)    
    print("a is b => ", a is b)    
    print("a is not b => ", a is not b)    
    print("a == b => ", a == b)    
    print("a != b => ", a != b)    
    

    Output:

    a is c => True
    a is not c => False
    a is b => False
    a is not b => True
    a == b => True
    a != b => False
    

    Operator Precedence

    The order in which the operators are examined is crucial to understand, since it tells us which operator needs to be considered first. Below is a list of the Python operators’ precedence tables.

    S. No.peratorDescription
    1**Overall other operators employed in the expression, the exponent operator is given precedence.
    2~, +, –the minus, unary plus, and negation.
    3*, /, %, //the division of the floor, the modules, the division, and the multiplication.
    4+, –Binary plus, and minus
    5>>, <<Left shift. and right shift
    6&Binary and.
    7^, |Binary xor, and or
    8<=, <, >, >=Comparison operators (less than, less than equal to, greater than, greater then equal to).
    9<>, ==, !=Equality operators.
    10=, %=, /=, //=, -=, +=,
    *=, **=
    Assignment operators
    11is, is notIdentity operators
    12in, not inMembership operators
    13not, or, andLogical operators

    Conclusion

    This article has covered all the operators in Python. We have briefly described the one-by-one operator in detail, including an example and the output for better understanding. Lastly, shared operator precedence to know which operator should be considered first. Python operators play an important role in calculation.

  • Literals in Python

    Python literals are fixed constant values assigned to variables or used directly in expression. The constant values are of varying types, such as numbers, strings, booleans, collections, or other special identifiers. Unlike the variables above, literals are immutable, which means they cannot be changed after being defined.

    Let us take a look at an example given below:

    Example

    x = 10  # Integer literal  
    print(x)  

    Output:

    10

    Here x = 10 is an integer literal.

    Types of Literals

    Literals are grouped under the following categories:

    1. Numeric Literals: Integers, floating points, and even complex numbers.
    2. String Literals: Literally any set of characters written in a string of quotes.
    3. Boolean Literals: The two most commonly accepted values, True or False.
    4. Collection Literals: Lists, tuples, dictionaries, and sets.
    5. Special Literal: The keyword None signifies the lack of value.

    Every single one of the aforementioned types of literals is of utmost importance for Python programming, and thus, knowing their usage and behaviour is fundamental for any developer.

    Numeric Literals

    Numeric literals are values that can be represented in Python, as their names suggest. They can be assigned different values and are further described in three categories:

    a) Integer (int)

    Integer literals are defined as whole numbers without any decimals. They can be negative, positive or zero. Python also allows the use of various formats of integer literals.

    1. Decimal (Base 10): Uses digits 0-9 (e.g., 100, -5, 0).
    2. Binary (Base 2): Prefixed with 0b or 0B (e.g., 0b1010 for decimal 10).
    3. Octal (Base 8): Prefixed with 0o or 0O (e.g., 0o12 for decimal 10).
    4. Hexadecimal (Base 16): Prefixed with 0x or 0X (e.g., 0xA for decimal 10).

    Example

    integer_num = 10      # Decimal integer  
    binary_num = 0b1010    # Binary integer  
    octal_num = 0o12       # Octal integer  
    hexadecimal_num = 0xA  # Hexadecimal integer  
      
    print(integer_num)  
    print(binary_num)  
    print(octal_num)  
    print(hexadecimal_num)  

    Output:

    10
    10
    10
    10

    In the above example, we have initialized multiple variables using different forms of integer literal and printed their values.

    b) Floating-Point (float)

    Floating-point literals represent numbers that contain a decimal point or are written in scientific notation. They are used for precise calculations involving fractions or real numbers.

    • Standard floating-point notation: (e.g., 3.14, -0.99, 2.5)
    • Scientific notation (exponential form): Uses e or E to indicate powers of 10 (e.g., 2.5e3 for 2500.0).

    Example

    float_num = 20.5       # Standard floating-point number  
    scientific_num = 2.5e3  # Equivalent to 2500.0  
    negative_float = -0.99  # Negative floating-point number  
      
    print(float_num)  
    print(scientific_num)  
    print(negative_float)  

    Output:

    20.5
    2500.0
    -0.99

    In the above example, we have initialized multiple variables using different floating-point literals and printed their values.

    c) Complex Numbers (complex)

    Python supports complex numbers, which consist of a real part and an imaginary part. The imaginary part is denoted using j or J.

    2. String Literals

    String literals in Python are sequences of characters enclosed in either single (‘ ‘), double (” “), or triple (”’ ”’ or “”” “””) quotes. They are used to store text data, including words, sentences, or even multi-line paragraphs.

    Types of String Literals:

    a) Single-Line Strings

    These are enclosed within single or double quotes and are used for short textual data.

    Example

    single_string = 'Hello'  # Single-quoted string  
    double_string = "Python"  # Double-quoted string  
      
    print(single_string)  
    print(double_string)  

    Output:

    Hello
    Python

    In the above example, we have initialized multiple variables using different format of single-line string literal and printed their values.

    b) Multi-Line Strings

    Multi-line strings are enclosed within triple single (”’ ”’) or triple-double (“”” “””) quotes. They are used when the text spans multiple lines, such as documentation or large text blocks.

    Example

    # multi-line string  
    multi_string = """This is a multi-line string. 
    It can span multiple lines. 
    Useful for documentation and long texts."""  
      
    print(multi_string)  

    Output:

    This is a multi-line string.
    It can span multiple lines.
    Useful for documentation and long texts.

    In the above example, we have initialized a multi-line string literal and printed its value.

    c) Escape Characters in Strings

    Python allows the use of escape characters to insert special characters within a string.

    • \n – Newline
    • \t – Tab
    • \’ – Single quote
    • \” – Double quote
    • \\ – Backslash

    Example

    escaped_string = 'Hello\nWorld'  # Inserts a new line  
    print(escaped_string)  

    Output:

    Hello
    World

    In the above example, we have initialized a multi-line string literal and printed its value.

    d) String Concatenation and Repetition

    Python allows strings to be combined using the + operator (concatenation) and repeated using the * operator.

    Example

    string1 = "Hello "  
    string2 = "World"  
    concatenated = string1 + string2  # "Hello World"  
    repeated = string1 * 3  # "Hello Hello Hello"  
      
    print(concatenated)  
    print(repeated)  

    Output:

    Hello World
    Hello Hello Hello

    In the above example, we have initialized two strings and then performed operations like concatenation and repetition.

    3.Boolean Literals

    Boolean literals represent truth values in Python. There are only two boolean literals:

    • True
    • False

    Example

    is_python_fun = True  # Boolean literal  
    is_raining = False  
      
    print(is_python_fun)  
    print(is_raining)  

    Output:

    True
    False

    In the above example, we have initialized and printed two variables with Boolean values.

    4. Collection Literals

    Collection literals represent groupings of values and include the following types:

    1. List Literals: Ordered and mutable collection (e.g., [1, 2, 3]).
    2. Tuple Literals: Ordered and immutable collection (e.g., (1, 2, 3)).
    3. Dictionary Literals: Key-value pairs (e.g., {‘name’: ‘Alice’, ‘age’: 25}).
    4. Set Literals: Unordered collection of unique items (e.g., {1, 2, 3}).

    Example

    list_literal = [10, 20, 30]  # List literal  
    tuple_literal = (10, 20, 30)  # Tuple literal  
    dict_literal = {'a': 1, 'b': 2}  # Dictionary literal  
    set_literal = {10, 20, 30}  # Set literal  
      
    print(list_literal)  
    print(tuple_literal)  
    print(dict_literal)  
    print(set_literal)  
    

    Output:

    [10, 20, 30]
    (10, 20, 30)
    {'a': 1, 'b': 2}
    {10, 20, 30}

    In the above example, we have initialized a list, tuple, dictionary and set and printed them for users.

    5. Special Literal

    Python has a special literal called None, which represents the absence of a value.

    Example

    value = None  # Special literal  
      
    print(value)  

    Output:

    None

    In the above example, we have initialized a variable with value set to None and printed it for users.

    Conclusion:

    Literals in Python are fundamental building blocks used to represent constant values in code. They include numeric literals (integers, floats, and complex numbers), string literals (single-line and multi-line strings), Boolean literals (True and False), collection literals (lists, tuples, dictionaries, and sets), and special literals (None). Understanding these literals helps programmers write more readable and efficient Python code. By leveraging different types of literals, you can store and manipulate data effectively while maintaining clarity in your programs.

  • Python Keywords

    Python keywords are reserved words used for specific purposes that have specific meanings and functions, and these keywords cannot be used for anything other than their specific use. These keywords are always available in Python, which means you don’t need to import them into the code.

    List of Python Keywords

    The following is the list of 35 keywords available in Python

    Falseawaitelseimportpass
    Nonebreakexceptinraise
    Trueclassfinallyisreturn
    andcontinueforlambdatry
    asdeffromnonlocalwhile
    assertdelglobalnotwith
    asyncelififoryield

    Let us discuss these keywords with the help of examples.

    Control Flow Keywords

    These Python keywords are utilized for decision-making and looping.

    Conditional Statements – if, elif, else

    These keywords are used to execute different blocks on the basis of conditions.

    KeywordDescription
    ifThis keyword is used to execute a block if the condition is True.
    elifThis keyword is used to specify additional conditions if the previous ones fail.
    elseThis keyword is used to execute a block if all previous conditions are False.

    Let us see an example showing how to use these keywords.

    # use of if, elif, else keywords  
      
    # initializing a variable  
    a = 20  
      
    # checking if the variable is greater than, equal to, or less than 20  
    if a > 20:  
        print("Greater than 20")  
    elif a == 20:  
        print("Equal to 20")  
    else:  
        print("Less than 20")  

    Output:

    Equal to 20

    Explanation:

    In the above example, we have initialized a variable and used the conditional statement keywords like if, elif, and else to check for the given condition and execute the code accordingly.

    Looping Construct – for, while

    These keywords are used to execute code repeatedly.

    KeywordDescription
    forThis keyword is used to iterate over a sequence, such as list, tuple, dictionary, etc.
    whileThis keyword is used to repeat execution while a condition remains True.

    Let us see an example showing how to use these keywords.

    Example

    
    # use of for, while keywords  
      
    # defining a list  
    shopping_bag = ['apples', 'bread', 'eggs', 'milk', 'coffee beans', 'tomatoes']  
    print("Given List:", shopping_bag)  
      
    print("\nIterating Over List using 'for' Loop:")  
    # iterating over the list using for loop  
    for item in shopping_bag:  
        print(item)  
      
    print("\nIterating Over List using 'while' Loop:")  
    # iterating over the list using while loop  
    index = 0  
    while index < len(shopping_bag):  
        print(shopping_bag[index])  
        index += 1  

    Output:

    Given List: ['apples', 'bread', 'eggs', 'milk', 'coffee beans', 'tomatoes']
    
    Iterating Over List using 'for' Loop:
    apples
    bread
    eggs
    milk
    coffee beans
    tomatoes
    
    Iterating Over List using 'while' Loop:
    apples
    bread
    eggs
    milk
    coffee beans
    tomatoes
    

    Explanation:

    In the above example, we have initialized a list and make use of the looping constructs like for and while to iterate over it.

    Loop Control – break, continue, pass

    The keywords under this classification are used to change the flow of execution inside a loop.

    KeywordDescription
    breakThis keyword immediately exits the loop.
    continueThis keyword is used to skip the current iteration and moves to the next.
    passThis keyword acts as a placeholder (does nothing).

    Let us see an example showing how to use these keywords.

    Example

    # use of break, continue, pass keywords  
      
    for i in range(20):  
      if i == 14:  
        break  # terminating the loop completely when i is 14  
      if i % 2 == 0:  
        continue  # skipping the rest of the loop for even numbers  
      if i == 9:  
        pass  # does nothing  
      
      print(i)  

    Output:

    1
    3
    5
    7
    9
    11
    13
    

    Explanation:

    In the above example, we have created a ‘for’ loop to print the numbers ranging from 0 to 20. Inside this loop, we have used the loop control keywords to change the flow of execution inside the loop. For instance, we have used the break keyword to terminate the entire loop when i becomes 14. The continue keyword is used to skips the loop for even numbers. We have used the pass keyword as a placeholder where the code can be added later.

    Function and Class Definition Keywords

    The keywords under this category are used to define functions, classes, and return values.

    KeywordDescription
    defThis keyword is used to define a function.
    returnThis keyword is used to return a value from a function.
    yieldThis keyword returns a generator object.
    lambdaThis keyword is used to define anonymous function.
    classThis keyword allows us to define a class.

    Let us see some examples showing how to use these keywords.

    Example: Use of def Keyword

    Let’s consider an example to demonstrate the def keyword in Python.

    Example

    # use of def keyword  
      
    # defining a function  
    def greeting():  
      print("Welcome to Learn Python App!")  
      
    # calling the function  
    greeting()  

    Output:

    Welcome to Learn Python App!

    Explanation:

    In the above example, we have defined a function to print a simple statement using the def keyword.

    Example: Use of return and yield Keyword

    Let’s take an example to demonstrate the return and yield keyword in Python.

    Example

    # use of return, yield keywords  
      
    # defining a function to add numbers  
    def add_numbers(num1, num2):  
      # using return keyword  
      return num1 + num2  
      
    # defining a function to generate number  
    def generate_number(num1):  
      for i in range(num1):  
        # using yield keyword  
        yield i  
      
    # printing results  
    print("Addition of 12 and 5 is", add_numbers(12, 5))  
      
    for i in generate_number(5):  
      print("Generated Number:", i)  

    Output:

    Addition of 12 and 5 is 17
    Generated Number: 0
    Generated Number: 1
    Generated Number: 2
    Generated Number: 3
    Generated Number: 4
    

    Explanation:

    In the above example, we have defined a function as add_numbers(), where we have used the return keyword to return the sum of the numbers passed to it. We have then defined another function as generate_number(), where we have used the yield keyword to return the generator object containing the list of numbers generated.

    Example: Use of lambda Keyword

    Let us take an example to demonstrate the lambda keyword in Python.

    Example

    # use of lambda keyword  
      
    # anonymous function using lambda  
    square_of_num = lambda num: num * num  
      
    # printing the result  
    print("Square of 12 is", square_of_num(12))  

    Output:

    Square of 12 is 144

    Explanation:

    In the above example, we have used the lambda keyword to define anonymous function to return the square of the number passed to it.

    Example: Use of class Keyword

    Let’s take an example to demonstrate the class keyword in Python.

    Example

    # use of class keyword  
      
    # declaring a user-defined class using class keyword  
    class Employer:  
      name = "Learn Python App"  
      industry = "Education"  


    Explanation:

    In this example, we have used the class keyword to declare a user-defined class using the keyword called class.

    Exception Handling Keywords

    The keywords under this category are used to handle errors and exceptions.

    KeywordDescription
    tryThis keyword is used to define a block to catch errors
    exceptThis keyword is used to handle exceptions
    finallyThis keyword helps execute after try-except
    raiseThis keyword is used to raise an exception manually
    assertThis keyword is used to define debugging statement

    Let us see an example showing how to use these keywords.

    Example

    # use of try, except, finally, raise, assert keyword  
      
    def func_one(x):  
      try:  
        assert x > 0, "x must be a positive number"  # AssertionError if x <= 0  
        result = 10 / x  # Might raise ZeroDivisionError  
      except ZeroDivisionError:  
        print("Error: Division by zero")  
        result = float('inf')  # handling error  
        raise  # re-raising the error  
      except AssertionError as e:  
        print(f"Assertion Error: {e}")  
        result = None  
      finally:  
        print("This will always execute")  
      return result  
      
    # printing results  
    print("For x = 6:", func_one(6), "\n")  
    print("For x = 0:", func_one(0), "\n")  
    print("For x = -6:", func_one(-6), "\n")  

    Output:

    This will always execute
    For x = 6: 1.6666666666666667
    
    Assertion Error: x must be a positive number
    This will always execute
    For x = 0: None
    
    Assertion Error: x must be a positive number
    This will always execute
    For x = -6: None
    

    Explanation:

    In the above example, we have defined a function. Inside this function, we have used the keywords like try, except, finally, raise, and assert to handle the different errors and exceptions that might raise during the execution of the function.

    Variable Scope and Namespace Keywords

    The keywords under this category are used for variable access and modification.

    KeywordDescription
    globalThis keyword is used to declare a global variable
    nonlocalThis keyword is used to modify parent function variables

    Let us see some examples showing how to use these keywords.

    Example: Use of global Keyword

    Let’s take an example to demonstrate the global keyword in Python.

    Example

    # use of global keyword  
      
    # initializing p as 12  
    p = 12  
      
    # defining a function  
    def func_one():  
      # using global keyword to declare p as global variable  
      global p  
      # updating the value of p to 19  
      p = 19  
      
    # printing results  
    func_one()  
    print(p)  

    Output:

    19

    Explanation:

    In the above example, we have initialized a variable and defined a function. Inside this function, we have used the global keyword to declare the initialized variable as global and updated its value.

    Example: Use of nonlocal Keyword

    Let’s consider an example to demonstrate the nonlocal keyword in Python.

    Example

    # use of nonlocal keyword  
      
    # defining an outer function  
    def func_outer():  
      # initializing p as 13  
      p = 13  
      # defining an inner function  
      def func_inner():  
        nonlocal p  # accessing the 'p' from the outer function  
        # updating the value of p to 25  
        p = 25  
        print("Inner function:", p)  
      
      # calling the inner function  
      func_inner()  
      print("Outer function:", p)  
      
    # calling the outer function  
    func_outer()  

    Output:

    Inner function: 25
    Outer function: 25
    

    Explanation:

    In the above example, we defined a nested function. Inside the outer function, we have initialized a variable. Inside the inner function, we have used the nonlocal keyword to modify the variable of the parent function.

    Logical and Boolean Keywords

    These keywords are used in logical operations and Boolean expressions.

    KeywordDescription
    andThis keyword represents Logical AND
    orThis keyword represents Logical OR
    notThis keyword represents Logical NOT
    TrueThis keyword represents Boolean True value
    FalseThis keyword represents Boolean False value

    Let us see an example showing how to use these keywords.

    Example: Use of Logical Operation Keywords

    Let’s consider an example to demonstrate the logical operation keywords in python.

    Example

    # use of and, or, not keywords  
      
    x = 12  
    y = 19  
      
    # Using 'and'  
    if x > 0 and y > 0:  
      print("Both x and y are positive")  
      
    # Using 'or'  
    if x > 15 or y > 15:  
      print("At least one of x or y is greater than 10")  
      
    # Using 'not'  
    if not x == 0:  
      print("x is not equal to 0")  

    Output:

    Both x and y are positive
    At least one of x or y is greater than 10
    x is not equal to 0
    

    Explanation:

    In the above example, we have initialized two variables and used the and, or, and not keywords to check various conditions.

    Example: Use of Boolean Expression Keywords

    Let’s consider an example to demonstrate the Boolean expression keywords in Python.

    Example

    # use of True, False keywords  
      
    # defining a function to check even number  
    def chck_even(number):  
      """Checks if a number is even."""  
      if number % 2 == 0:  
        return True  
      else:  
        return False  
      
    print(f"Is 24 even? {chck_even(24)}")  
    print(f"Is 57 even? {chck_even(57)}")  

    Output:

    Is 24 even? True
    Is 57 even? False
    

    Explanation:

    In the above example, we have defined function to check for even number. Inside this function, we have used the True keyword to return that given variable is an even number and False in case of odd number.

    Import and Module Keywords

    The keywords under this category are used for module handling and importing functions.

    KeywordDescription
    importThis keyword is used to import a module
    fromThis keyword allows us to import specific part of a module
    asThis keyword is used to rename imported module

    Let us see an example showing how to use these keywords.

    Example

    # use of import, from, as keywords  
      
    import math as m  
    from math import pi  
    Explanation:
    
    In the above example, we have used the import, from, and as keywords to handle the importing functions.
    
    
    

    Inheritance and Comparison Keywords
    The keywords under this category are used for class inheritance and object relationships.

    KeywordDescription
    isThis keyword is used to check if two objects are the same
    inThis keyword is used to check membership in lists, tuples, etc.

    Example

    # use of is, in keywords  
      
    p = 14  
    q = 14  
      
    # 'is' checks if both variables refer to the same object in memory  
    if p is q:  
      print("p and q refer to the same object")  
      
    # 'in' checks for membership in a sequence (string, list, tuple, etc.)  
    lst_1 = [13, 25, 46, 14, 59]  
    if p in lst_1:  
      print("p is present in lst_1")  

    Output:

    p and q refer to the same object
    p is present in lst_1
    

    Explanation:

    In the above example, we have initialized two variables. We have then used the is and in keywords to check if both variables refer to the same object and member of a given list.

    Asynchronous Programming Keywords

    These keywords are used for asynchronous programming.

    KeywordDescription
    asyncThis keyword is used to define an asynchronous function.
    awaitThis keyword allows us to pause async function execution

    Let us see an example showing how to use these keywords.

    Example

    # use of async, await keywords  
      
    # importing the required module  
    import asyncio  
      
    async def greeting():  
      print("Learn Python
    ")  
      await asyncio.sleep(1)  # pausing for 1 second without blocking  
      print("App")  
      
    async def main():  
      await greeting()  # waiting for greeting to finish  
      
    await main()  

    Output:

    Learn Python
    App

    Explanation:

    In the above example, we have imported the asyncio module. We have then used the async keyword while defining asynchronous functions. We have also used the await keyword to pause the execution of async functions.

    Python Program to Print All Keywords

    As per Python 3.11, there are 35 keywords. Here, we are going to take an example to print all keywords in Python.

    Example

    # importing the keyword module  
    import keyword  
      
    # using kwlist to display list of keywords  
    print(keyword.kwlist)  
    

    Output:

    ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

    Explanation:

    In the above, we have used the kwlist attribute from the keyword module to get the list of keywords in Python.

    What are Soft Keywords in Python?

    Python also includes four soft keywords, which act like keywords only under certain conditions. Unlike regular keywords, these keywords can still be utilized in the form of variable names or function identifiers.

    For instance, the keywords like match and case were introduced for the purpose of structural pattern matching. However, since they are soft keywords, we can used them as variable names in non-pattern-matching contexts.

    Conclusion

    Python keywords are reserved words having special meanings and are central to the syntax and structure of a language. They provide important programming concepts such as control flow, manipulation of data, and function declaration. Good knowledge of these keywords are important in writing clean, and readable code.

  • Python Syntax

    Python Syntax acts as grammar, with the set of rules defining the way of writing and organizing code so that the Python interpreter can understand and execute it properly. These rules ensure that the code is well-written, structured, and error-free. Python, being a powerful, high-level programming language has a simple and highly readable syntax, making it a popular choice for beginners and professionals alike.

    First Program in Python

    We will now look at the basic Python program to print “Hello, world!” in two different modes:

    • Interactive Mode
    • Script Mode

    Python Interactive Mode

    We can use Python interpreter from command line by simply typing ‘python’ as shown below:

    Syntax:

    C:\> python  
    
    Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb  4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32  
    
    Type "help", "copyright", "credits" or "license" for more information.  
    
    >>>

    In the above syntax, >>> denotes a Python Command Prompt where we can type the commands. Let us now write a simple syntax to print “Hello, World!” in Python prompt and press Enter.

    Example

    >>> print("Hello, World!")

    Output:

    Hello, World!

    Python Script Mode

    Another method to use Python Interpreter is by using the Python Script mode. In script mode the code is written in a .py file and then executed from the command prompt. Let us now write a simple syntax to print “Hello, World!” using the script mode and save it as sample.py.

    Example

    print("Hello, World!")  
    1. Output:
    $ python sample.py
    Hello, World!
    

    Different Aspects of Python Syntax:

    The following are the different aspects of Python Syntax:

    • Variables
    • Indentation
    • Identifiers
    • Keywords
    • Comments
    • Multiline Statements
    • Input from Users

    Python Variables

    Variables in Python are used to store data values. Unlike other languages, Python variables do not require explicit declaration of type; they are dynamically typed. This means that the type of variable is determined at runtime based on the value assigned to it.

    Let us see a simple example showing the way of defining variables in Python.

    Example

    # initializing variables 
    a = 10  
    
    print(a, '->', type(a))    
    
      
    
    b = 'Learn Python App'    
    
    print(b, '->', type(b))  

    Output:

    10 -> <class 'int'>
    Learn Python App -> <class 'str'>

    Explanation:

    In the above example, we have defined two variables of different data types. As we can observe, we have not declared their data types explicitly.

    To learn more about Variables and their data types in Python, visit – Python Variables and Python Data Types.

    Indentation in Python

    Python uses indentation to define blocks of code instead of using curly braces {} as in other languages like C or Java. Indentation enhances code readability and is a crucial part of Python syntax. Every block of code (such as loops, functions, and conditionals) must be indented at the same level.

    Example

    if 9 > 5:  
    
      print("9 is greater than 5")      # proper indentation  
    
      print("This is part of the if block")  
    
    print("This is outside the if block")

    Output:

    9 is greater than 5
    This is part of the if block
    This is outside the if block
    

    Explanation:

    In the above example, we have used the if statement to check if 9 is greater than 5. If true, it will print the indented line of codes.

    In case of improper indentation, it will raise an IndentationError. Proper indentation ensures the logical structure of the code is maintained.

    Python Identifiers

    Identifiers are names used for variables, functions, classes, and other entities in Python. They must follow specific rules to be valid:

    1. It can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
    2. It cannot start with a digit.
    3. We cannot use Python keywords as identifiers.
    4. Case-sensitive (MyVar and myvar are different identifiers).
    5. It should be descriptive and follow naming conventions (e.g., using snake_case for variables and functions and CamelCase for class names).

    Python Keywords

    Keywords are reserved words in Python that cannot be used as variable names. Examples include if, else, while, for, def, class, import, etc.

    FalseNoneTrueand
    assertasawaitasync
    breakclasscontinuedef
    delelifelseexcept
    finallyforfromglobal
    ifimportnotin
    returnyieldwhilewith
    raiseorpasstry
    islambdanonlocalmatch
    case   

    To learn more about Keywords, visit – Python Keywords

    Python Comments

    Comments in Python are used to explain code and make it more readable. They help other developers understand the purpose of the code and serve as a reminder for the programmer. Comments are ignored by the Python interpreter, meaning they do not affect the execution of the program.

    Here is an example showing different types of comments in Python.

    Example

    # This is a single-line comment  
    
      
    
    """This is a multi-line comment. 
    
    It can span multiple lines. 
    
    """  
    
      
    
    def addition():  
    
      # This is a comment inside a function  
    
      a = 10  # This is an inline comment  
    
      '''''This is a multi-line string, often used for documentation. 
    
      It can also serve as a multi-line comment. 
    
      '''  
    
      b = 14  
    
      print("Sum of a and b is", a + b)  
    
      
    
    addition()

    Output:

    Sum of a and b is 24

    Explanation:

    In the above example, the line followed by the # symbol is treated as comments. As a result, it is ignored by the interpreter. Moreover, the multiline comments declared using the triple quotes are often considered as docstrings.

    To learn more about Comments, visit – Python Comments

    Multiline Statements in Python

    Writing a long statement in a code is not good practice causing unreadability. To prevent this, we can break the long line of code into multiple lines. This can be done either explicitly using backslash (\) or implicitly by parentheses ().

    A backslash (\) in Python is a special character used to indicate line continuation. It allows long lines of code to be split across multiple lines for better readability without affecting the code’s execution.

    Let us take a look at the following example showing how backslash (\) works in Python.

    Example

    # showing the use of backslash (\) to break   
    
    # the long line of code into multiple lines  
    
    total_cost = 25 + 58 + 92 + \  
    
                 74 + 29 + 82 + \  
    
                 51 + 99 + 12  
    
    print(total_cost) 

      Output:

      522

      Explanation:

      In the above example, we have used the backslash (\) to split the long line of code into multiple lines in order to increase the readability of the code.

      To learn more about multiline statements, visit – Multi-Line Statements in Python

      Taking Input from User in Python

      In Python, we use the input() function to take user input. The input is always received as a string, even if the user enters a number.

      Let us see the following example showing how to take input from the users in Python.

      Example

      # taking input from user  
      
      fname = input("Enter your first name: ")  
      
      lname = input("Enter your last name: ")  
      
      print("Welcome,", fname, lname)

      Output:

      Enter your first name: Tony
      Enter your last name: Prince
      Welcome, Tony Prince

      Explanation:

      In the above example, we have used the input() function to take input from the user.

      Conclusion

      Python syntax is simple, highly readable, and enforces indentation for code structure, making it beginner-friendly yet powerful for professionals. Its flexibility, dynamic typing, and clear formatting enhance code efficiency and maintainability.

    1. How to Install Python?

      Python is among the most widely used programming languages. Due to its user-friendliness, readability, and extensive library ecosystem, whether you are a novice or an expert developer, the first step to accomplish this is to install Python on Windows if you wish to write and execute Python programs.

      Here, we are going to learn how to install Python on Windows step-by-step.

      Installing Python on Windows

      Python doesn’t come with prepackage in Windows, but it doesn’t mean that Window user cannot be flexible with Python. Some operating systems such as Linux come with the Python package manager that can run to install Python. Below are the steps to install Python in Windows.

      Step 1: Downloading the Installer for Python

      To install Python on Windows, you first have to take the Python installer from the internet.

      Visit the official website of Python:

      • Open your favourite web browser, be it Google Chrome, Edge, or Firefox.
      • Go to the official site for downloading Python at: http://www.python.org/downloads/
      • The website will automatically check what operating system you are using and provide the most recent stable version of Python for Windows users
      Python Environment Set-up

      Choose the Correct Version

      Selecting the appropriate version

      • Latest stable releases, such as Python 3.13.2, are recommended for all users.
        Python Environment Set-up
      • To view the older version, scroll down the page and click on “View all Python releases.”

      1.3 Installer Download

      • To begin, click on the button that has the “Download Python 3.13.2” text.
        Python Environment Set-up
      • An exe file indicative of an executable will be downloaded (for example, python-3.13.2.exe).

      Step 2: Running of the Python Installer

      After downloading the installer file, you have to run it.

      2.1 Finding the Installer

      • Go to the directory of the downloaded folder (usually, it is in the Downloads folder).
      • To start the installation process, double-click on the exe file.
        Python Environment Set-up

      2.2 Selecting Installation Preferences

      Upon the appearance of the setup window of Python, these options will be available: You have to do these things:

      1. There is “Add Python to PATH,” which you will be required to check the box next to it.

      This step must be done with utmost care as it is very critical.

      • Checking this box will ensure that using the command prompt, you can control the use of Python at any given location or position.

      2. Decide from the given options:

      • (default) “Install Now” Installs with the default options selected.
      • “Customize installation” where you get the freedom to set different options for the installation.
      • From options 1 and 2, if you are a starter, it is best that you click on “Install Now” to install with the pre-set options.

      2.3 Commencing Installation

      • To begin the installation, select “Install now.”
        Python Environment Set-up
      • At this point, your system will have Python files copied into it.

      Step 3: Installation Completion Duration

      The whole process might take a few minutes.

      • After completing the process, the statement “Setup was successful” will appear.
      • To exit the installer, click on the “Close” button.

      Step 4: Verify Python Installation

      To successfully confirm that Python was installed, kindly follow the procedure listed below:

      4.1 Open Command Prompt

      • Open the Command Prompt window by pressing Win + R, followed by typing cmd and pressing Enter.

      4.2 Check Python Version

      To check if the application was successfully installed, type the following command and press enter:
      
      $ python --version  
      
      In the event Python was installed properly, it will show the following:
      Python Environment Set-up

      3.9.7 (where the number following 3 is the version number)

      In the situation that the command yields an error, it may indicate that Python is not added to the system PATH.

      Step 5: Verify pip Installation

      Pip is known as a package manager, which enables the installation and management of Python libraries.

      5.1 Check if pip is Installed

      • Command Prompt can be opened by typing:
      $ pip --version  
      Python Environment Set-up

      Step 6: Test Python with the Command Prompt

      In an effort to test if Python is working correctly, attempt to run basic Python scripts.

      1. Command Prompt (cmd) can be opened.

      2. Type:

      $ python  

      A Python interactive shell page will open, revealing the Python version with “>>>” following it.

      3. Type the following statement:

      print("Hello World!")  

      4. Assuming that Python was installed properly, it will show:

      1. Hello, World!  
      Python Environment Set-up

      5. To close Python, the following command can be used:

      exit()  

      Conclusion:

      You have successfully installed Python on your Windows operating system. You can now start coding in Python, adding new libraries, and creating new projects.

    2. Hello World Program in Python

      In this section, we will learn how to write the simple program of Python to print the classic “Hello, World!” on the console.

      Python Hello World Program

      Here’s the “Hello, World!” program:

      Example

       # simple "Hello, World!" program in Python  
      # using the print() function to print the text "Hello, World!"  
      print("Hello, World!")  

      Output:

      Hello, World!

      Code Explanation

      Hello World Program in Python

      In the above snippet of code, we have used print(), a built-in function in Python, to display output to the user. “Hello, World!” is a string literal. It’s the text we want to display, enclosed within double quotes. The print() function takes this string as input and displays it.

      Things to Remember While Writing First Python Program

      The following are few key concepts to remember while writing programs in Python:

      1. Indentation: Python uses indentation in order to define code blocks. Unlike other programming languages that make use of parentheses {} or keywords, Python uses proper indentation in the form of spaces or tabs for the code to function correctly. Moreover, it also improves the readability of the code.
      2. Dynamic Typing: Python is dynamically typed language. This means that we are not required to declare the data types of variables explicitly. For example, x = 10 is an integer, but assigning x = “hello” later changes it to a string.
      3. Virtual Environments: Python supports virtual environments (venv) which helps isolating the dependencies for different projects. This also helps preventing package conflicts and ensuring each project runs with the required library versions.
      4. Extensive Library Support: Python offers a rich set of built-in libraries like math, itertools, datetime, collections, and functools, enabling efficient problem-solving without reinventing the wheel.
      5. PEP 8: Python’s official style guide promotes best practices such as meaningful variable names, consistent indentation, proper spacing, and a 79-character line limit for better code readability and maintainability.

      Different Ways to Print “Hello, World!” in Python

      1. Using a User-defined Function

      In this example, we are defining our own function and printing Hello, World! from inside it.

      Example

      def show_message():  
          print("Hello, World!")  
      show_message()  
      Output:
      
      Hello, World!
      

      2. Using String Assignment and Print

      In this example, we are first storing the message in a string variable and then printing it.

      Example

      msg = "Hello, World!"  
      print(msg)  
      
      Output:

      Hello, World!

      Conclusion

      In the following tutorial, we have learned the use of print() function to print a simple statement: “Hello, World!”. We have discussed various key points to remember while writing programs in Python. We have also looked at some more examples of Python illustrating the use of print() function.

    3. Applications of Python Programming

      Python contributes its importance in a variety of applications because of its various features, which make Python highly readable, easy to use and maintain, manageable, and reusable. Python plays a vital role in the field of gaming, web development, and Data Analytics, and plays a major role in the field of Artificial Intelligence (AI), Machine Learning (ML), and Automation.

      Python has been the preferred language for developers in the following areas:-

      Python Applications
      • Web Development
      • Data Science
      • Web Scrapping
      • Automation
      • CAD
      • Artificial Intelligence and Machine Learning
      • Game Development
      • Networking and Cybersecurity
      • Data Analytics

      Web Development

      Python is a highly recommended language for web development because of its simplicity, readability and many built-in features like libraries and packages. Python offers frameworks like Django, Flask and Pyramid, which make Python more flexible and easy to maintain.

      Python Applications

      Django provides a built-in admin panel by which developers do not need to code from scratch; they can easily add, delete or edit the data. Django Restful APIs help to create web APIs that support both ORM and non-ORM data sources.

      Data Science

      Python Applications

      Data science is a broader field that surrounds data engineering, machine learning, and other fields like data analytics. Many built-in libraries make the mathematical calculations easier and efficient data analysis. Libraries such as Pandas, NumPy, Matplotlib, and SciPy.

      Web Scraping

      Basically, web scraping is the process of extracting data from websites automatically with the help of software tools. There are many key libraries that are used for web scraping in Python, such as:

      Python Applications
      • Requests: For making HTTP requests to fetch web page content.
      • BeautifulSoup:Used for parsing HTML and XML documents and navigating their structure.
      • Scrapy: It is a powerful tool for webscraping, but can be considered a framework for building complex web crawlers and scrapers.
      • Selenium:It heavily relies on JavaScript and interacts with dynamic websites. It automates the browser actions.
      • Lxml: parsing their HTML or XML content using the lxml library.

      The data which are extracted from other resources has to be stored somewhere, so there are libraries in Python that provide a way to store extracted data in various formats, such as CSV, JSON, or a database, using libraries like CSV and JSON.

      Automation

      Automation is the key application of Python, which focuses on performing tasks automatically and reducing the need for manual intervention. This can include automation in vast areas related to web applications and robotics.

      Python Applications

      The day-to-day tasks come into action through technology, or we can say, through programming. Machines learns from their environment and perform tasks automatically according to action.

      Computer-Aided Design (CAD)

      CAD stands for Computer-Aided Design, which is used to create 2-Dimensional and 3-Dimensional models of the product or website. Architects, construction managers, and product designers use this application to build things with extremely high consistency, which has replaced manual drift.

      Python Applications

      Python comes with support for fantastic applications such as Blender, Open Cascade, FreeCAD, and many others that help us design products quickly. Features like technical drawing, dynamic system development, and data import are all greatly enhanced.

      Artificial Intelligence

      Python Applications

      Python plays a vital and significant role in the field of AI and ML because of its extensive built-in libraries and ease of use. AI is a broad concept of making machines that can act, think, and behave like humans. They can make decisions according to the situation or the course of action and perform tasks automatically. Examples of AI include natural language processing, computer vision, and robotics.

      Machine Learning

      Python Applications

      ML is a subset of AI; it is considered the learning of machines from daily life and past actions without explicit programming. ML algorithms analyse data, identify patterns, and make predictions or decisions based on that data. Examples of ML include spam filtering, recommendation systems, and fraud detection.

      Game Development

      Python Applications

      Python is a feasible option for game development because of its predefined built-in libraries like Pygame, Pygame Zero, and Arcade, which simplify game development and allow beginners to easily develop 2-dimensional games. However, Python is not ideal or highly demanding for developing 3-dimensional or high graphics games due to potential performance limitations.

      Networking and Cybersecurity

      Python Applications

      Python is also playing a role in the field of networking and cybersecurity. Python is a powerful tool for networking and cybersecurity because it contains many libraries and frameworks that ease the automation, data analysis, and security tasks. Libraries like Paramiko, Netmiko, and NAPALM are used for routers, switches, and firewalls, and Scapy is used for packet sniffing, crafting, and sending.

      Data Analytics

      Python Applications

      Today, data analytics is trending, and Python is extensively used in data analytics for processing, examining, cleaning, transforming, and modelling data. The key aspects of data analytics are Data collection and loading, Data Visualization, Data Manipulation and Transformation, statistical Analysis, and key Python libraries.

      Conclusion

      As we saw the applications of Python. It is an almost highly effective language in each field of software. You can use Python for web development, gaming, data scraping, and in the field of AI and ML, which is highly productive. As you know, Python has many built-in libraries, packages, and tools that make Python a versatile, flexible, and powerful programming language.

    4. History of Python Programming Language

      Python is a widely used general-purpose, high-level programming language created by Guido van Rossum in 1991. It was primarily developed to improve the readability of code, allowing developers to write codes in fewer lines.

      Who Invented Python?

      Python was created by Guido van Rossum, a Dutch programmer, in the late 1980s. He was an employee at Centrum Wiskunde & Informatica in the Netherlands. His goal was to create an advanced scripting language based on ABC that was easy to understand and could be used and added to easily. The initial public release, Python 0.9.0, was published in February 1991.

      What is the History of Python?

      Van Rossum started developing Python in December of 1989 with the goal of creating a computer programming language that has:

      • Simple and precise syntax
      • Straightforward data structures
      • Dynamic typing and allocation of memory
      • Standard library that serves a wide range of needs

      The first public version, Python 0.9.0, was released in February 1991, and it was the first to offer functions, modules, exception handling, and dynamic typing – making it possible for users to program what they wanted with ease.

      Objectives of Development of Python

      Throughout the development phase, Van Rossum made several important choices which affected the design of Python:

      • Interpreted Programming Language: Python does not need compilation like languages like C or Java, and that makes coding and debugging much easier.
      • Whitespace is Important: Python lets its users define indentation as a part of the syntax; this helps improve the organization of code and is more readable.
      • Extensibility: Other languages like C can easily be integrated into Python, giving it and the programmers wider capabilities.
      • Object-Oriented and Procedural: Python can incorporate measures from different programming paradigms like procedural and object-oriented programming.
      • Community Focused Development: Van Rossum made Python open source from the very beginning, which has made it easier for the community to contribute without any restrictions.

      Why is Python called Python?

      In the late 1980s, while developing the language, Guido van Rossum chose the name “Python.” It is often thought that the word ‘python’ refers to the snake. However, it refers to the British sitcom, ‘Monty Python’s Flying Circus.

      Why Did Van Rossum Choose This Name?

      • Good wordplay: Van Rossum was a fan of the overall British witty comedy which goes beyond the traditional standup humour of Monty Python.
      • Mystery: Van Rossum wanted a name that had a certain level of mystery around it as opposed to being overly technical or boring.
      • Freedom: Monty Python, the sitcom, was known for not censoring the content they produced, and this aligns with the entire philosophy of python.

      Evolution of Python

      Like many programming languages, Python has undergone considerable practice over the years, resulting in significant improvements in its performance alongside its functionality and usability. Here’s a summary of major evolution stages captured in the different versions of Python:

      History of Python Programming Language

      Python 1.x (1991-2000)

      • Python’s first version (1.0) was later released in January 1994.
      • Notable characteristics comprised of dynamic typing, modules, methods, and exception handling.
      • The basic principles of simplicity and readability, which the language is known for was founded.

      Python 2.x (2000-2010)

      • In October 2000, the second version came out; Python 2.0.
      • Added features such as support for Unicode, garbage collector, and list comprehension.
      • Python 2.0 did preserve backward compatibility but also had some shortcomings that led to the formation of Python 3.
      • Python 2.0 was shelved on January 1st, 2020.

      Python 3.x (2008-Present)

      • The third version came out in December 2008, version 3.0.
      • Great improvements were added on the Python interface like:
      • Added and improved support for Unicode
      • Use of the print() function instead of the print statement
      • Improved division for integers
      • Better Structured standard library
      • Use of type hinting
      • Today, the driving force behind the latest Python versions are performance and usability.

      Latest Python Versions

      Below is a table showcasing the most recent Python versions and their release dates:

      VersionRelease DateKey Features
      Python 3.6December 2016f-strings, type hints, improved async support
      Python 3.7June 2018Data classes, improved asyncio, performance boosts
      Python 3.8October 2019Walrus operator (:=), positional-only arguments
      Python 3.9October 2020Dictionary union operators, type hinting improvements
      Python 3.10October 2021Pattern matching, structural pattern matching
      Python 3.11October 2022Performance improvements, enhanced error messages
      Python 3.12October 2023More performance enhancements, security updates
      Python 3.13October 2024New language features, further optimizations
      Python 3.13.2February 2025Free-threaded mode (PEP 703), experimental Just-In-Time (JIT) compiler (PEP 744), bug fixes

      Conclusion:

      Today, Python is among the most impactful programming languages regarding its application and use worldwide. Since its initial inception by Guido van Rossum in the late 1980s, Python has consistently iterated on its versions with improvements on functionality, ease of use, and general efficiency. Its flexible applicability across various domains means that for web development, data science, artificial intelligence, and even automation, it is undoubtedly the most popular programming language.

      Python is highly relevant in modern day computing technology owing to strong community support and regular updates, which will further ensure its usefulness for many more years to come. With every new version released, innovations and new features are added to improve performance, and because of this, Python will continue being a crucial part of programming for years to come.

    5. Advantages of Python

      Python is a high-level dynamic programming language. It is interpreted and focuses on code readability. There are fewer steps compared to Java and C. In 1991, it was founded by Guido Van Rossum, a developer. Python is one of the most popular and rapidly growing programming languages. Python is a programming language that is powerful, adaptable, and easy to learn. Python also has a vibrant community. Because it supports a wide range of programming paradigms, it is widely found in various businesses. It also automatically manages memory.

      Easy to Learn and Use

      For Beginners, Python is simple to understand and use. It’s a highly developed programming language with an English-like syntax. The language is simple to adapt as a result of these factors. Because of its simplicity, Python’s fundamentals can be implemented faster than those in other programming languages.

      Free and Open-Source

      Python is distributed under an open-source license approved by the Open-Source Initiative (OSI). As a result, users can work on it and distribute it. Users can download the source code, modify it, and even distribute their Python version. Companies that wish to modify a specific behavior and build their version will benefit.

      Rapid Development

      Users can create new kinds of applications using the Python programming language. Because of its versatility, this language permits the operator to try new things. Because of the language, the user is not prevented from trying something new. Python is favored in these scenarios since other programming languages lack the flexibility and freedom that Python does.

      Interpreted Language

      Python is an interpreted language, implying that the code is implemented line by line. This is one of the features that makes it simple to use. In the event of an error, it halts the process and reports the problem. Python only shows one error, even if the program has multiple errors. This makes debugging easier.

      Wide Range of Libraries and Frameworks

      Python includes a huge number of libraries that the user can use. The standard library in Python is immense, and it includes almost every function imaginable. Large and supportive communities, as well as corporate sponsorship, have contributed to this. When working with Python, users do not need to use external libraries.

      Dynamically Typed

      Until we run the program, Python has no idea what kinds of parameter we’re talking about. It allocates the data type automatically during execution. Variables and their data types do not need to be declared by the programmer.

      Portability

      Many other languages, including C/C++, demand that user must change their code to run on different platforms. Python, on the contrary, is not equivalent to other programming languages. It only needs to be written once, and then it can be run anywhere. However, the user should avoid involving any system-dependent features.

      Strong Community Support

      Python is a programming language generated many years ago and has a large community that can assist programmers of all experience levels, from rookies to specialists. Python’s community has helped it grow quickly in comparison to other languages. The Python programming language comes with many guides, instructional videos, and highly understandable documentation to help developers learn the language faster and more effectively.

      Other main and important advantages of Python language are:

      • Cross-Platform Compatibility
      • Strong Community Support
      • Integration and Extensibility
      • Scalability and Performance
      • Versatility and Flexibility

      Conclusion

      Python is a popular programming language that is both concise and powerful. It has been at the forefront of cutting-edge technologies such as artificial intelligence, automation, and deep learning. It’s also used to help with hot topics like data analysis and visualization. We’ve attempted to give the reader a basic understanding of this blog’s top 10 real-world Python applications.