Blog

  • Python Operators

    Introduction:

    In this article, we are discussing Python Operators. The operator is a symbol that performs a specific operation between two operands, according to one definition. Operators serve as the foundation upon which logic is constructed in a program in a particular programming language. In every programming language, some operators perform several tasks. Same as other languages, Python also has some operators, and these are given below –

    • Arithmetic operators
    • Comparison operators
    • Assignment Operators
    • Logical Operators
    • Bitwise Operators
    • Membership Operators
    • Identity Operators
    • Arithmetic Operators

    Arithmetic Operators

    Arithmetic operators used between two operands for a particular operation. There are many arithmetic operators. It includes the exponent (**) operator as well as the + (addition), – (subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.

    Consider the following table for a detailed explanation of arithmetic operators.

    OperatorDescription
    + (Addition)It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
    – (Subtraction)It 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 = 15
    / (divide)It returns the quotient after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a/b = 2.0
    * (Multiplication)It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 80
    % (reminder)It returns the reminder after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a%b = 0
    ** (Exponent)As it calculates the first operand’s power to the second operand, it is an exponent operator.
    // (Floor division)It provides the quotient’s floor value, which is obtained by dividing the two operands.

    Program Code:

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

    a = 32    # Initialize the value of a  
    
    b = 6      # Initialize the value of b  
    
    print('Addition of two numbers:',a+b)  
    
    print('Subtraction of two numbers:',a-b)  
    
    print('Multiplication of two numbers:',a*b)  
    
    print('Division of two numbers:',a/b)  
    
    print('Reminder of two numbers:',a%b)  
    
    print('Exponent of two numbers:',a**b)  
    
    print('Floor division of two numbers:',a//b)

    Output:

    Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Addition of two numbers: 38 Subtraction of two numbers: 26 Multiplication of two numbers: 192 Division of two numbers: 5.333333333333333 Reminder of two numbers: 2 Exponent of two numbers: 1073741824 Floor division of two numbers: 5

    Comparison operator

    Comparison operators mainly use for comparison purposes. Comparison operators compare the values of the two operands and return a true or false Boolean value in accordance. The example of comparison operators are ==, !=, <=, >=, >, <. In the below table, we explain the works of the operators.

    OperatorDescription
    ==If the value of two operands is equal, then the condition becomes true.
    !=If the value of two operands is not equal, then the condition becomes true.
    <=The condition is met if the first operand is smaller than or equal to the second operand.
    >=The condition is met if the first operand is greater than or equal to the second operand.
    >If the first operand is greater than the second operand, then the condition becomes true.
    <If the first operand is less than the second operand, then the condition becomes true.

    Program Code:

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

    a = 32      # Initialize the value of a  
    
    b = 6       # Initialize the value of b  
    
    print('Two numbers are equal or not:',a==b)  
    
    print('Two numbers are not equal or not:',a!=b)  
    
    print('a is less than or equal to b:',a<=b)  
    
    print('a is greater than or equal to b:',a>=b)  
    
    print('a is greater b:',a>b)  
    
    print('a is less than 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 -Two numbers are equal or not: False Two numbers are not equal or not: True a is less than or equal to b: False a is greater than or equal to b: True a is greater b: True a is less than b: False

    Assignment Operators

    Using the assignment operators, the right expression’s value is assigned to the left operand. There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below table, we explain the works of the operators.

    OperatorDescription
    =It assigns the value of the right expression to the left operand.
    +=By multiplying the value of the right operand by the value of the left operand, the left operand receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
    -=It decreases the value of the left operand by the value of the right operand and assigns the modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
    *=It multiplies the value of the left operand by the value of the right operand and assigns the modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
    %=It divides the value of the left operand by the value of the right operand and assigns the reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
    **=a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
    //=A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

    Program Code:

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

    a = 32         # Initialize the value of a  
    
    b = 6          # Initialize the value of 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)  
    
    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: False a+=b: 38 a-=b: 26 a*=b: 192 a%=b: 2 a**=b: 1073741824 a//=b: 5

    Bitwise Operators

    The two operands’ values are processed bit by bit by the bitwise operators. The examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift (>>). Consider the case below.

    For example,

    if a = 7       
    
       b = 6         
    
    then, binary (a) = 0111        
    
        binary (b) = 0110        
    
            
    
    hence, a & b = 0011        
    
          a | b = 0111        
    
                 a ^ b = 0100        
    
           ~ a = 1000      
    
    Let, Binary of x = 0101  
    
          Binary of y = 1000  
    
    Bitwise OR = 1101  
    
    8 4 2 1  
    
    1 1 0 1 = 8 + 4 + 1 = 13  
    
      
    
    Bitwise AND = 0000  
    
    0000 = 0  
    
      
    
    Bitwise XOR = 1101  
    
    8 4 2 1  
    
    1 1 0 1 = 8 + 4 + 1 = 13  
    
    Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6  
    
    ~x = -6

    In the below table, we are explaining the works of the bitwise operators.

    OperatorDescription
    & (binary and)A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is copied.
    | (binary or)The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
    ^ (binary xor)If the two bits are different, the outcome bit will be 1, else it will be 0.
    ~ (negation)The operand’s bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and vice versa.
    << (left shift)The number of bits in the right operand is multiplied by the leftward shift of the value of the left operand.
    >> (right shift)The left operand is moved right by the number of bits present in the right operand.

    Program Code:

    a = 5          # initialize the value of a  
    
    b = 6          # initialize the value of b  
    
    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:

    Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -a&b: 4 a|b: 7 a^b: 3 ~a: -6 a<>b: 0

    Logical Operators

    The assessment of expressions to make decisions typically uses logical operators. The examples of logical operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend upon the second one. In the case of logical OR, if the first one is 1, it does not depend on the second one. Python supports the following logical operators. In the below table, we explain the works of the logical operators.

    OperatorDescription
    andThe condition will also be true if the expression is true. If the two expressions a and b are the same, then a and b must both be true.
    orThe condition will be true if one of the phrases is true. If a and b are the two expressions, then an or b must be true if and is true and b is false.
    notIf an expression a is true, then not (a) will be false and vice versa.

    Program Code:

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

    a = 5          # initialize the value of a          
    
    print(Is this statement true?:',a > 3 and a < 5)  
    
    print('Any one statement is true?:',a > 3 or a < 5)  
    
    print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))

    Output:

    Now we give code examples of Bitwise operators in Python. The code is given below -Is this statement true?: False Any one statement is true?: True Each statement is true then return False and vice-versa: True

    Membership Operators

    The membership of a value inside a Python data structure can be verified using Python membership operators. The result is true if the value is in the data structure; otherwise, it returns false.

    OperatorDescription
    inIf the first operand cannot be found in the second operand, it is evaluated to be true (list, tuple, or dictionary).
    not inIf the first operand is not present in the second operand, the evaluation is true (list, tuple, or dictionary).

    Program Code:

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

    x = ["Rose", "Lotus"]  
    
    print(' Is value Present?', "Rose" in x)  
    
    print(' Is value not Present?', "Riya" not in x)

    Output:

    Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Is value Present? True Is value not Present? True

    Identity Operators

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

    Program Code:

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

    a = ["Rose", "Lotus"]  
    
    b = ["Rose", "Lotus"]  
    
    c = a  
    
    print(a is c)  
    
    print(a is not c)  
    
    print(a is b)  
    
    print(a is not b)  
    
    print(a == b)  
    
    print(a != b)

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -True False False True True 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.

    OperatorDescription
    **Overall other operators employed in the expression, the exponent operator is given precedence.
    ~ + –the minus, unary plus, and negation.
    * / % //the division of the floor, the modules, the division, and the multiplication.
    + –Binary plus, and minus
    >> <<Left shift. and right shift
    &Binary and.
    ^ |Binary xor, and or
    <= < > >=Comparison operators (less than, less than equal to, greater than, greater then equal to).
    <> == !=Equality operators.
    = %= /= //= -= +=
    *= **=
    Assignment operators
    is is notIdentity operators
    in not inMembership operators
    not or andLogical operators

    Conclusion:

    So, in this article, we are discussing all the Python Operators. We briefly discuss how they work and share the program code using each operator in Python.

  • Python Literals

    Python Literals can be defined as data that is given in a variable or constant.

    Python supports the following literals:

    1. String literals:

    String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes to create a string.

    Example:

    "Aman" , '12345'  

    Types of Strings:

    There are two types of Strings supported in Python:

    a) Single-line String– Strings that are terminated within a single-line are known as Single line Strings.

    Example:

    text1='hello'  

    b) Multi-line String – A piece of text that is written in multiple lines is known as multiple lines string.

    There are two ways to create multiline strings:

    1) Adding black slash at the end of each line.

    Example:

    text1='hello\    
    
    user'    
    
    print(text1)

    ‘hellouser’

    2) Using triple quotation marks:-

    Example:

    str2='''''welcome  
    
    to  
    
    SSSIT'''    
    
    print str2

    Output:welcome to SSSIT

    II. Numeric literals:

    Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

    Int(signed integers)Long(long integers)float(floating point)Complex(complex)
    Numbers( can be both positive and negative) with no fractional part.eg: 100Integers of unlimited size followed by lowercase or uppercase L eg: 87032845LReal numbers with both integer and fractional part eg: -26.2In the form of a+bj where a forms the real part and b forms the imaginary part of the complex number. eg: 3.14j

    Example – Numeric Literals

    x = 0b10100 #Binary Literals  
    
    y = 100 #Decimal Literal   
    
    z = 0o215 #Octal Literal  
    
    u = 0x12d #Hexadecimal Literal  
    
      
    
    #Float Literal  
    
    float_1 = 100.5   
    
    float_2 = 1.5e2  
    
      
    
    #Complex Literal   
    
    a = 5+3.14j  
    
      
    
    print(x, y, z, u)  
    
    print(float_1, float_2)  
    
    print(a, a.imag, a.real)

    Output:20 100 141 301 100.5 150.0 (5+3.14j) 3.14 5.0

    III. Boolean literals:

    A Boolean literal can have any of the two values: True or False.

    Example – Boolean Literals

    
    
    1. x = (1 == True)  
    2. y = (2 == False)  
    3. z = (3 == True)  
    4. a = True + 10  
    5. b = False + 10  
    6.   
    7. print("x is", x)  
    8. print("y is", y)  
    9. print("z is", z)  
    10. print("a:", a)  
    11. print("b:", b)  

    Output:x is True y is False z is False a: 11 b: 10

    IV. Special literals.

    Python contains one special literal i.e., None.

    None is used to specify to that field that is not created. It is also used for the end of lists in Python.

    Example – Special Literals

    val1=10    
    
    val2=None    
    
    print(val1)     
    
    print(val2)

    Output:10 None

    V. Literal Collections.

    Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals, and Set literals.

    List:

    • List contains items of different data types. Lists are mutable i.e., modifiable.
    • The values stored in List are separated by comma(,) and enclosed within square brackets([]). We can store different types of data in a List.

    Example – List literals

    
    
    1. list=['John',678,20.4,'Peter']    
    2. list1=[456,'Andrew']    
    3. print(list)    
    4. print(list + list1)  

    Output:[‘John’, 678, 20.4, ‘Peter’] [‘John’, 678, 20.4, ‘Peter’, 456, ‘Andrew’]

    Dictionary:

    • Python dictionary stores the data in the key-value pair.
    • It is enclosed by curly-braces {} and each pair is separated by the commas(,).

    Example

    dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}  
    
    print(dict)

    Output:{‘name’: ‘Pater’, ‘Age’: 18, ‘Roll_nu’: 101}

    Tuple:

    • Python tuple is a collection of different data-type. It is immutable which means it cannot be modified after creation.
    • It is enclosed by the parentheses () and each element is separated by the comma(,).

    Example

    tup = (10,20,"Dev",[2,3,4])  
    
    print(tup)

    Output:(10, 20, ‘Dev’, [2, 3, 4])

    Set:

    • Python set is the collection of the unordered dataset.
    • It is enclosed by the {} and each element is separated by the comma(,).

    Example: – Set Literals

    set = {'apple','grapes','guava','papaya'}  
    
    print(set)

    Output:{‘guava’, ‘apple’, ‘papaya’, ‘grapes’}

  • Python Keywords

    Every scripting language has designated words or keywords, with particular definitions and usage guidelines. Python is no exception. The fundamental constituent elements of any Python program are Python keywords.

    This tutorial will give you a basic overview of all Python keywords and a detailed discussion of some important keywords that are frequently used.

    Introducing Python Keywords

    Python keywords are unique words reserved with defined meanings and functions that we can only apply for those functions. You’ll never need to import any keyword into your program because they’re permanently present.

    Python’s built-in methods and classes are not the same as the keywords. Built-in methods and classes are constantly present; however, they are not as limited in their application as keywords.

    Assigning a particular meaning to Python keywords means you can’t use them for other purposes in our code. You’ll get a message of SyntaxError if you attempt to do the same. If you attempt to assign anything to a built-in method or type, you will not receive a SyntaxError message; however, it is still not a smart idea.

    Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have shown a complete list of Python keywords for the reader’s reference.

    Falseawaitelseimportpass
    Nonebreakexceptinraise
    Trueclassfinallyisreturn
    andcontinueforlambdatry
    asdeffromnonlocalwhile
    assertdelglobalnotwith
    asyncelififoryield

    In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced, while others may be deleted. By writing the following statement into the coding window, you can anytime retrieve the collection of keywords in the version you are working on.

    Code

    # Python program to demonstrate the application of iskeyword()  
    
    # importing keyword library which has lists  
    
    import keyword  
    
        
    
    # displaying the complete list using "kwlist()."  
    
    print("The set of keywords in this version is: ")  
    
    print( keyword.kwlist )

    Output:The set of keywords in this version is : [‘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’]

    By calling help(), you can retrieve a list of currently offered keywords:

    Code

    help("keywords")  

    How to Identify Python Keywords

    Python’s keyword collection has evolved as new versions were introduced. The await and async keywords, for instance, were not introduced till Python 3.7. Also, in Python 2.7, the words print and exec constituted keywords; however, in Python 3+, they were changed into built-in methods and are no longer part of the set of keywords. In the paragraphs below, you’ll discover numerous methods for determining whether a particular word in Python is a keyword or not.

    Write Code on a Syntax Highlighting IDE

    There are plenty of excellent Python IDEs available. They’ll all highlight keywords to set them apart from the rest of the terms in the code. This facility will assist you in immediately identifying Python keywords during coding so that you do not misuse them.

    Verify Keywords with Script in a REPL

    There are several ways to detect acceptable Python keywords plus know further regarding them in the Python REPL.

    Look for a SyntaxError

    Lastly, if you receive a SyntaxError when attempting to allocate to it, name a method with it, or do anything else with that, and it isn’t permitted, it’s probably a keyword. This one is somewhat more difficult to see, but it is still a technique for Python to tell you if you’re misusing a keyword.

    Python Keywords and Their Usage

    The following sections categorize Python keywords under the headings based on their frequency of use. The first category, for instance, includes all keywords utilized as values, whereas the next group includes keywords employed as operators. These classifications will aid in understanding how keywords are employed and will assist you in arranging the huge collection of Python keywords.

    • A few terms mentioned in the segment following may be unfamiliar to you. They’re explained here, and you must understand what they mean before moving on:
    • The Boolean assessment of a variable is referred to as truthfulness. A value’s truthfulness reveals if the value of the variable is true or false.

    In the Boolean paradigm, truth refers to any variable that evaluates to true. Pass an item as an input to bool() to see if it is true. If True is returned, the value of the item is true. Strings and lists which are not empty, non-zero numbers, and many other objects are illustrations of true values.

    False refers to any item in a Boolean expression that returns false. Pass an item as an input to bool() to see if it is false. If False is returned, the value of the item is false. Examples of false values are ” “, 0, { }, and [ ].

    Value Keywords: True, False, None

    Three Python keywords are employed as values in this example. These are singular values, which we can reuse indefinitely and every time correspond to the same entity. These values will most probably be seen and used frequently.

    The Keywords True and False

    These keywords are typed in lowercase in conventional computer languages (true and false); however, they are typed in uppercase in Python every time. In Python script, the True Python keyword represents the Boolean true state. False is a keyword equivalent to True, except it has the negative Boolean state of false.

    True and False are those keywords that can be allocated to variables or parameters and are compared directly.

    Code

    print( 4 == 4 )  
    
    print( 6 > 9 )  
    
    print( True or False )  
    
    print( 9 <= 28 )  
    
    print( 6 > 9 )  
    
    print( True and False )

    Output:True False True True False False

    Because the first, third, and fourth statements are true, the interpreter gives True for those and False for other statements. True and False are the equivalent in Python as 1 & 0. We can use the accompanying illustration to support this claim:

    Code

    print( True == 3 )  
    
    print( False == 0 )  
    
    print( True + True + True)

    Output:False True 3

    The None Keyword

    None is a Python keyword that means “nothing.” None is known as nil, null, or undefined in different computer languages.

    If a function does not have a return clause, it will give None as the default output:

    Code

    
    
    1. print( None == 0 )  
    2. print( None == " " )  
    3. print( None == False )  
    4. A = None   
    5. B = None  
    6. print( A == B )  

    Output:False False False True

    If a no_return_function returns nothing, it will simply return a None value. None is delivered by functions that do not meet a return expression in the program flow. Consider the following scenario:

    Code

    def no_return_function():  
    
        num1 = 10  
    
        num2 = 20  
    
        addition = num1 + num2  
    
      
    
    number = no_return_function()  
    
    print( number )

    Output:None

    This program has a function with_return that performs multiple operations and contains a return expression. As a result, if we display a number, we get None, which is given by default when there is no return statement. Here’s an example showing this:

    Code

    def with_return( num ):  
    
        if num % 4 == 0:  
    
            return False  
    
      
    
    number = with_return( 67 )  
    
    print( number )

    Output:None

    Operator Keywords: and, or, not, in, is

    Several Python keywords are employed as operators to perform mathematical operations. In many other computer languages, these operators are represented by characters such as &, |, and!. All of these are keyword operations in Python:

    Mathematical OperationsOperations in Other LanguagesPython Keyword
    AND, ∧&&and
    OR, ∨||or
    NOT, ¬!not
    CONTAINS, ∈in
    IDENTITY===is

    Writers created Python programming with clarity in mind. As a result, many operators in other computer languages that employ characters in Python are English words called keywords.

    The and Keyword

    The Python keyword and determines whether both the left-hand side and right-hand side operands and are true or false. The outcome will be True if both components are true. If one is false, the outcome will also be False:

    Truth table for and
    XYX and Y
    TrueTrueTrue
    FalseTrueFalse
    TrueFalseFalse
    FalseFalseFalse

    1. <component1> and <component2>  

    It’s worth noting that the outcomes of an and statement aren’t always True or False. Due to and’s peculiar behavior, this is the case. Instead of processing the inputs to corresponding Boolean values, it just gives <component1> if it is false or <component2> if it is true. The outputs of a and expression could be utilized with a conditional if clause or provided to bool() to acquire an obvious True or False answer.

    The or Keyword

    The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the first argument is true, the or operation yields it; otherwise, the second argument is returned:

    <component1> or <component2>  

    Similarly to the and keyword, the or keyword does not change its inputs to corresponding Boolean values. Instead, the outcomes are determined based on whether they are true or false.

    Truth table for or
    XYX or Y
    TrueTrueTrue
    TrueFalseTrue
    FalseTrueTrue
    FalseFalseFalse

    The not Keyword

    The not keyword in Python is utilized to acquire a variable’s contrary Boolean value:

    The not keyword is employed to switch the Boolean interpretation or outcome in conditional sentences or other Boolean equations. Not, unlike and, and or, determines the specific Boolean state, True or False, afterward returns the inverse.

    Truth Table for not
    Xnot X
    TrueFalse
    FalseTrue

    Code

    False and True  
    
    False or True  
    
    not True

    Output:False True False

    The in Keyword

    The in keyword of Python is a robust confinement checker, also known as a membership operator. If you provide it an element to seek and a container or series to seek into, it will give True or False, depending on if that given element was located in the given container:

    <an_element> in <a_container>  

    Testing for a certain character in a string is a nice illustration of how to use the in keyword:

    Code

    container = "Javatpoint"  
    
    print( "p" in container )  
    
    print( "P" in container )

    Output:True False

    Lists, dictionaries, tuples, strings, or any data type with the method __contains__(), or we can iterate over it will work with the in keyword.

    The is Keyword

    In Python, it’s used to check the identification of objects. The == operation is used to determine whether two arguments are identical. It also determines whether two arguments relate to the unique object.

    When the objects are the same, it gives True; otherwise, it gives False.

    Code

    
    
    1. print( True is True )  
    2. print( False is True )  
    3. print( None is not None )  
    4. print( (9 + 5) is (7 * 2) )  

    Output:True False False True

    True, False, and None are all the same in Python since there is just one version.

    Code

    print( [] == [] )  
    
    print( [] is [] )  
    
    print( {} == {} )  
    
    print( {} is {} )

    Output:True False True False

    A blank dictionary or list is the same as another blank one. However, they aren’t identical entities because they are stored independently in memory. This is because both the list and the dictionary are changeable.

    Code

    print( '' == '' )  
    
    print( '' is '' )

    Output:True True

    Strings and tuples, unlike lists and dictionaries, are unchangeable. As a result, two equal strings or tuples are also identical. They’re both referring to the unique memory region.

    The nonlocal Keyword

    Nonlocal keyword usage is fairly analogous to global keyword usage. The keyword nonlocal is designed to indicate that a variable within a function that is inside a function, i.e., a nested function is just not local to it, implying that it is located in the outer function. We must define a non-local parameter with nonlocal if we ever need to change its value under a nested function. Otherwise, the nested function creates a local variable using that title. The example below will assist us in clarifying this.

    Code

    def the_outer_function():  
    
        var = 10  
    
        def the_inner_function():  
    
            nonlocal var  
    
            var = 14  
    
            print("The value inside the inner function: ", var)  
    
        the_inner_function()  
    
        print("The value inside the outer function: ", var)  
    
      
    
    the_outer_function()

    Output:The value inside the inner function: 14 The value inside the outer function: 14

    the_inner_function() is placed inside the_outer_function in this case.

    The the_outer_function has a variable named var. Var is not a global variable, as you may have noticed. As a result, if we wish to change it inside the the_inner_function(), we should declare it using nonlocal.

    As a result, the variable was effectively updated within the nested the_inner_function, as evidenced by the results. The following is what happens if you don’t use the nonlocal keyword:

    def the_outer_function():  
    
        var = 10  
    
        def the_inner_function():  
    
            var = 14  
    
            print("Value inside the inner function: ", var)  
    
        the_inner_function()  
    
        print("Value inside the outer function: ", var)  
    
      
    
    the_outer_function()

    Output:Value inside the inner function: 14 Value inside the outer function: 10

    Iteration Keywords: for, while, break, continue

    The iterative process and looping are essential programming fundamentals. To generate and operate with loops, Python has multiple keywords. These would be utilized and observed in almost every Python program. Knowing how to use them correctly can assist you in becoming a better Python developer.

    The for Keyword

    The for loop is by far the most popular loop in Python. It’s built by blending two Python keywords. They are for and in, as previously explained.

    The while Keyword

    Python’s while loop employs the term while and functions similarly to other computer languages’ while loops. The block after the while phrase will be repeated repeatedly until the condition following the while keyword is false.

    The break Keyword

    If you want to quickly break out of a loop, employ the break keyword. We can use this keyword in both for and while loops.

    The continue Keyword

    You can use the continue Python keyword if you wish to jump to the subsequent loop iteration. The continue keyword, as in many other computer languages, enables you to quit performing the present loop iteration and go on to the subsequent one.

    Code

    # Program to show the use of keywords for, while, break, continue  
    
    for i in range(15):  
    
        
    
        print( i + 4, end = " ")  
    
            
    
        # breaking the loop when i = 9  
    
        if i == 9:  
    
            break     
    
    print()  
    
            
    
    # looping from 1 to 15  
    
    i = 0 # initial condition  
    
    while i < 15:  
    
            
    
        # When i has value 9, loop will jump to next iteration using continue. It will not print  
    
        if i == 9:  
    
            i += 3  
    
            continue  
    
        else:  
    
            # when i is not equal to 9, adding 2 and printing the value  
    
            print( i + 2, end = " ")  
    
                
    
        i += 1

    Output:4 5 6 7 8 9 10 11 12 13 2 3 4 5 6 7 8 9 10 14 15 16

    Exception Handling Keywords – try, except, raise, finally, and assert

    try: This keyword is designed to handle exceptions and is used in conjunction with the keyword except to handle problems in the program. When there is some kind of error, the program inside the “try” block is verified, but the code in that block is not executed.

    except: As previously stated, this operates in conjunction with “try” to handle exceptions.

    finally: Whatever the outcome of the “try” section, the “finally” box is implemented every time.

    raise: The raise keyword could be used to specifically raise an exception.

    assert: This method is used to help in troubleshooting. Often used to ensure that code is correct. Nothing occurs if an expression is interpreted as true; however, if it is false, “AssertionError” is raised. An output with the error, followed by a comma, can also be printed.

    Code

    # initializing the numbers  
    
    var1 = 4  
    
    var2 = 0  
    
        
    
    # Exception raised in the try section  
    
    try:  
    
        d = var1 // var2 # this will raise a "divide by zero" exception.  
    
        print( d )  
    
    # this section will handle exception raised in try block  
    
    except ZeroDivisionError:  
    
        print("We cannot divide by zero")  
    
    finally:  
    
        # If exception is raised or not, this block will be executed every time  
    
        print("This is inside finally block")  
    
    # by using assert keyword we will check if var2 is 0  
    
    print ("The value of var1 / var2 is : ")  
    
    assert var2 != 0, "Divide by 0 error"  
    
    print (var1 / var2)

    Output:We cannot divide by zero This is inside finally block The value of var1 / var2 is : ————————————————————————— AssertionError Traceback (most recent call last) Input In [44], in () 15 # by using assert keyword we will check if var2 is 0 16 print (“The value of var1 / var2 is : “) —> 17 assert var2 != 0, “Divide by 0 error” 18 print (var1 / var2) AssertionError: Divide by 0 error

    The pass Keyword

    In Python, a null sentence is called a pass. It serves as a stand-in for something else. When it is run, nothing occurs.

    Let’s say we possess a function that has not been coded yet however we wish to do so in the long term. If we write just this in the middle of code,

    Code

    def function_pass( arguments ):  

    Output:def function_pass( arguments ): ^ IndentationError: expected an indented block after function definition on line 1

    as shown, IndentationError will be thrown. Rather, we use the pass command to create a blank container.

    Code

    def function_pass( arguments ):  
    
        pass

    We can use the pass keyword to create an empty class too.

    Code

    class passed_class:  
    
        pass

    The return Keyword

    The return expression is used to leave a function and generate a result.

    The None keyword is returned by default if we don’t specifically return a value. The accompanying example demonstrates this.

    Code

    def func_with_return():  
    
        var = 13  
    
        return var  
    
      
    
    def func_with_no_return():  
    
        var = 10  
    
      
    
    print( func_with_return() )  
    
    print( func_with_no_return() )

    Output:13 None

    The del Keyword

    The del keyword is used to remove any reference to an object. In Python, every entity is an object. We can use the del command to remove a variable reference.

    Code

    var1 = var2 = 5  
    
    del var1  
    
    print( var2 )  
    
    print( var1 )

    Output:5 ————————————————————————— NameError Traceback (most recent call last) Input In [42], in () 2 del var1 3 print( var2 ) —-> 4 print( var1 ) NameError: name ‘var1’ is not defined

    We can notice that the variable var1’s reference has been removed. As a result, it’s no longer recognized. However, var2 still exists.

    Deleting entries from a collection like a list or a dictionary is also possible with del:

    list_ = ['A','B','C']  
    
    del list_[2]  
    
    print(list_)

    Output:[‘A’, ‘B’]

  • Python Data Types

    Every value has a datatype, and variables can hold values. Python is a powerfully composed language; consequently, we don’t have to characterize the sort of variable while announcing it. The interpreter binds the value implicitly to its type.

    a = 5  

    We did not specify the type of the variable a, which has the value five from an integer. The Python interpreter will automatically interpret the variable as an integer.

    We can verify the type of the program-used variable thanks to Python. The type() function in Python returns the type of the passed variable.

    Consider the following illustration when defining and verifying the values of various data types.

    a=10  
    
    b="Hi Python"  
    
    c = 10.5  
    
    print(type(a))  
    
    print(type(b))  
    
    print(type(c))

    Output:<type ‘int’> <type ‘str’> <type ‘float’>

    Standard data types

    A variable can contain a variety of values. On the other hand, a person’s id must be stored as an integer, while their name must be stored as a string.

    The storage method for each of the standard data types that Python provides is specified by Python. The following is a list of the Python-defined data types.

    1. Numbers
    2. Sequence Type
    3. Boolean
    4. Set
    5. Dictionary
    Python Data Types

    The data types will be briefly discussed in this tutorial section. We will talk about every single one of them exhaustively later in this instructional exercise.

    Numbers

    Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with a Python Numbers datatype. Python offers the type() function to determine a variable’s data type. The instance () capability is utilized to check whether an item has a place with a specific class.

    a = 5  
    
    print("The type of a", type(a))  
    
      
    
    b = 40.5  
    
    print("The type of b", type(b))  
    
      
    
    c = 1+3j  
    
    print("The type of c", type(c))  
    
    print(" c is a complex number", isinstance(1+3j,complex))

    Output:The type of a <class ‘int’> The type of b <class ‘float’> The type of c <class ‘complex’> c is complex number: True

    Python supports three kinds of numerical data.

    • Int: Whole number worth can be any length, like numbers 10, 2, 29, – 20, – 150, and so on. An integer can be any length you want in Python. Its worth has a place with int.
    • Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15 decimal places.
    • Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

    Sequence Type

    String

    The sequence of characters in the quotation marks can be used to describe the string. A string can be defined in Python using single, double, or triple quotes.

    String dealing with Python is a direct undertaking since Python gives worked-in capabilities and administrators to perform tasks in the string.

    When dealing with strings, the operation “hello”+” python” returns “hello python,” and the operator + is used to combine two strings.

    Because the operation “Python” *2 returns “Python,” the operator * is referred to as a repetition operator.

    The Python string is demonstrated in the following example.

    Example – 1

    str = "string using double quotes"  
    
    print(str)  
    
    s = '''''A multiline 
    
    string'''  
    
    print(s)

    Output:string using double quotes A multiline string

    Look at the following illustration of string handling.

    Example – 2

    str1 = 'hello javatpoint' #string str1    
    
    str2 = ' how are you' #string str2    
    
    print (str1[0:2]) #printing first two character using slice operator    
    
    print (str1[4]) #printing 4th character of the string    
    
    print (str1*2) #printing the string twice    
    
    print (str1 + str2) #printing the concatenation of str1 and str2

    Output:he o hello javatpointhello javatpoint hello javatpoint how are you

    List

    Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the rundown are isolated with a comma (,) and encased inside square sections [].

    To gain access to the list’s data, we can use slice [:] operators. Like how they worked with strings, the list is handled by the concatenation operator (+) and the repetition operator (*).

    Look at the following example.

    Example:

    list1  = [1, "hi", "Python", 2]    
    
    #Checking type of given list  
    
    print(type(list1))  
    
      
    
    #Printing the list1  
    
    print (list1)  
    
      
    
    # List slicing  
    
    print (list1[3:])  
    
      
    
    # List slicing  
    
    print (list1[0:2])   
    
      
    
    # List Concatenation using + operator  
    
    print (list1 + list1)  
    
      
    
    # List repetation using * operator  
    
    print (list1 * 3)

    Output:[1, ‘hi’, ‘Python’, 2] [2] [1, ‘hi’] [1, ‘hi’, ‘Python’, 2, 1, ‘hi’, ‘Python’, 2] [1, ‘hi’, ‘Python’, 2, 1, ‘hi’, ‘Python’, 2, 1, ‘hi’, ‘Python’, 2]

    Tuple

    In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data types. A parenthetical space () separates the tuple’s components from one another.

    Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.

    Let’s look at a straightforward tuple in action.

    Example:

    tup  = ("hi", "Python", 2)    
    
    # Checking type of tup  
    
    print (type(tup))    
    
      
    
    #Printing the tuple  
    
    print (tup)  
    
      
    
    # Tuple slicing  
    
    print (tup[1:])    
    
    print (tup[0:1])    
    
      
    
    # Tuple concatenation using + operator  
    
    print (tup + tup)    
    
      
    
    # Tuple repatation using * operator  
    
    print (tup * 3)     
    
      
    
    # Adding value to tup. It will throw an error.  
    
    t[2] = "hi"

    Output:<class ‘tuple’> (‘hi’, ‘Python’, 2) (‘Python’, 2) (‘hi’,) (‘hi’, ‘Python’, 2, ‘hi’, ‘Python’, 2) (‘hi’, ‘Python’, 2, ‘hi’, ‘Python’, 2, ‘hi’, ‘Python’, 2) Traceback (most recent call last): File “main.py”, line 14, in <module> t[2] = “hi”; TypeError: ‘tuple’ object does not support item assignment

    Dictionary

    A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an associative array or a hash table. Value is any Python object, while the key can hold any primitive data type.

    The comma (,) and the curly braces are used to separate the items in the dictionary.

    Look at the following example.

    
    
    1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}     
    2.   
    3. # Printing dictionary  
    4. print (d)  
    5.   
    6. # Accesing value using keys  
    7. print("1st name is "+d[1])   
    8. print("2nd name is "+ d[4])    
    9.   
    10. print (d.keys())    
    11. print (d.values())    

    Output:1st name is Jimmy 2nd name is mike {1: ‘Jimmy’, 2: ‘Alex’, 3: ‘john’, 4: ‘mike’} dict_keys([1, 2, 3, 4]) dict_values([‘Jimmy’, ‘Alex’, ‘john’, ‘mike’])

    Boolean

    True and False are the two default values for the Boolean type. These qualities are utilized to decide the given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or the letter “F,” while true can be represented by any value that is not zero.

    Look at the following example.

    # Python program to check the boolean type  
    
    print(type(True))  
    
    print(type(False))  
    
    print(false)

    Output:<class ‘bool’> <class ‘bool’> NameError: name ‘false’ is not defined

    Set

    The data type’s unordered collection is Python Set. It is iterable, mutable(can change after creation), and has remarkable components. The elements of a set have no set order; It might return the element’s altered sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to create the set or the built-in function set() is used to create the set. It can contain different kinds of values.

    Look at the following example.

    # Creating Empty set  
    
    set1 = set()  
    
      
    
    set2 = {'James', 2, 3,'Python'}  
    
      
    
    #Printing Set value  
    
    print(set2)  
    
      
    
    # Adding element to the set  
    
      
    
    set2.add(10)  
    
    print(set2)  
    
      
    
    #Removing element from the set  
    
    set2.remove(2)  
    
    print(set2)

    Output:{3, ‘Python’, ‘James’, 2} {‘Python’, ‘James’, 3, 2, 10} {‘Python’, ‘James’, 3, 10}

  • Python Variables

    A variable is the name given to a memory location. A value-holding Python variable is also known as an identifier.

    Since Python is an infer language that is smart enough to determine the type of a variable, we do not need to specify its type in Python.

    Variable names must begin with a letter or an underscore, but they can be a group of both letters and digits.

    The name of the variable should be written in lowercase. Both Rahul and rahul are distinct variables.

    Identifier Naming

    Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the program. The standards to name an identifier are given underneath.

    • The variable’s first character must be an underscore or alphabet (_).
    • Every one of the characters with the exception of the main person might be a letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
    • White space and special characters (!, @, #, %, etc.) are not allowed in the identifier name. ^, &, *).
    • Identifier name should not be like any watchword characterized in the language.
    • Names of identifiers are case-sensitive; for instance, my name, and MyName isn’t something very similar.
    • Examples of valid identifiers: a123, _n, n_9, etc.
    • Examples of invalid identifiers: 1a, n%4, n 9, etc.

    Declaring Variable and Assigning Values

    • Python doesn’t tie us to pronounce a variable prior to involving it in the application. It permits us to make a variable at the necessary time.
    • In Python, we don’t have to explicitly declare variables. The variable is declared automatically whenever a value is added to it.
    • The equal (=) operator is utilized to assign worth to a variable.

    Object References

    When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared to a lot of other programming languages, the procedure for dealing with variables is a little different.

    Python is the exceptionally object-arranged programming language; Because of this, every data item is a part of a particular class. Think about the accompanying model.

    print("John")  

    Output:John

    The Python object makes a integer object and shows it to the control center. We have created a string object in the print statement above. Make use of the built-in type() function in Python to determine its type.

    type("John")  

    Output:<class ‘str’>

    In Python, factors are an symbolic name that is a reference or pointer to an item. The factors are utilized to indicate objects by that name.

    Let’s understand the following example

    a = 50   

    Python Variables

    In the above image, the variable a refers to an integer object.

    Suppose we assign the integer value 50 to a new variable b.

    a = 50  
    
    b = a
    Python Variables

    The variable b refers to the same object that a points to because Python does not create another object.

    Let’s assign the new value to b. Now both variables will refer to the different objects.

    a = 50  
    
    b =100
    Python Variables

    Python manages memory efficiently if we assign the same variable to two different values.

    Object Identity

    Every object created in Python has a unique identifier. Python gives the dependable that no two items will have a similar identifier. The object identifier is identified using the built-in id() function. consider about the accompanying model.

    a = 50  
    
    b = a  
    
    print(id(a))  
    
    print(id(b))  
    
    # Reassigned variable a  
    
    a = 500  
    
    print(id(a))

    Output:140734982691168 140734982691168 2822056960944

    We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check returned the same number. We reassign a to 500; The new object identifier was then mentioned.

    Variable Names

    The process for declaring the valid variable has already been discussed. Variable names can be any length can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_). Take a look at the names of valid variables in the following example.

    name = "Devansh"  
    
    age = 20  
    
    marks = 80.50  
    
      
    
    print(name)  
    
    print(age)  
    
    print(marks)

    Output:Devansh 20 80.5

    Consider the following valid variables name.

    name = "A"  
    
    Name = "B"  
    
    naMe = "C"  
    
    NAME = "D"  
    
    n_a_m_e = "E"  
    
    _name = "F"  
    
    name_ = "G"  
    
    _name_ = "H"  
    
    na56me = "I"  
    
      
    
    print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)

    Output:A B C D E D E F G F I

    We have declared a few valid variable names in the preceding example, such as name, _name_, and so on. However, this is not recommended because it may cause confusion when we attempt to read code. To make the code easier to read, the name of the variable ought to be descriptive.

    The multi-word keywords can be created by the following method.

    • Camel Case – In the camel case, each word or abbreviation in the middle of begins with a capital letter. There is no intervention of whitespace. For example – nameOfStudent, valueOfVaraible, etc.
    • Pascal Case – It is the same as the Camel Case, but here the first word is also capital. For example – NameOfStudent, etc.
    • Snake Case – In the snake case, Words are separated by the underscore. For example – name_of_student, etc.

    Multiple Assignment

    Multiple assignments, also known as assigning values to multiple variables in a single statement, is a feature of Python.

    We can apply different tasks in two ways, either by relegating a solitary worth to various factors or doling out numerous qualities to different factors. Take a look at the following example.

    1. Assigning single value to multiple variables

    Eg:

    x=y=z=50    
    
    print(x)    
    
    print(y)    
    
    print(z)

    Output:50 50 50

    2. Assigning multiple values to multiple variables:

    Eg:

    a,b,c=5,10,15    
    
    print a    
    
    print b    
    
    print c

    Output:5 10 15

    The values will be assigned in the order in which variables appear.

    Python Variable Types

    There are two types of variables in Python – Local variable and Global variable. Let’s understand the following variables.

    Local Variable

    The variables that are declared within the function and have scope within the function are known as local variables. Let’s examine the following illustration.

    Example –

    # Declaring a function  
    
    def add():  
    
        # Defining local variables. They has scope only within a function  
    
        a = 20  
    
        b = 30  
    
        c = a + b  
    
        print("The sum is:", c)  
    
      
    
    # Calling a function  
    
    add()

    Output:The sum is: 50

    Explanation:

    We declared the function add() and assigned a few variables to it in the code above. These factors will be alluded to as the neighborhood factors which have scope just inside the capability. We get the error that follows if we attempt to use them outside of the function.

    add()  
    
    # Accessing local variable outside the function   
    
    print(a)

    Output:The sum is: 50 print(a) NameError: name ‘a’ is not defined

    We tried to use local variable outside their scope; it threw the NameError.

    Global Variables

    Global variables can be utilized all through the program, and its extension is in the whole program. Global variables can be used inside or outside the function.

    By default, a variable declared outside of the function serves as the global variable. Python gives the worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local variable if we don’t use the global keyword. Let’s examine the following illustration.

    Example –

    # Declare a variable and initialize it  
    
    x = 101  
    
      
    
    # Global variable in function  
    
    def mainFunction():  
    
        # printing a global variable  
    
        global x  
    
        print(x)  
    
        # modifying a global variable  
    
        x = 'Welcome To Javatpoint'  
    
        print(x)  
    
      
    
    mainFunction()  
    
    print(x)

    Output:101 Welcome To Javatpoint Welcome To Javatpoint

    Explanation:

    In the above code, we declare a global variable x and give out a value to it. We then created a function and used the global keyword to access the declared variable within the function. We can now alter its value. After that, we gave the variable x a new string value and then called the function and printed x, which displayed the new value.=

    Delete a variable

    We can delete the variable using the del keyword. The syntax is given below.

    Syntax –

    del <variable_name>  

    In the following example, we create a variable x and assign value to it. We deleted variable x, and print it, we get the error “variable x is not defined”. The variable x will no longer use in future.

    Example –

    # Assigning a value to x  
    
    x = 6  
    
    print(x)  
    
    # deleting a variable.   
    
    del x  
    
    print(x)

    Output:6 Traceback (most recent call last): File “C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py”, line 389, in print(x) NameError: name ‘x’ is not defined

    Maximum Possible Value of an Integer in Python

    Python, to the other programming languages, does not support long int or float data types. It uses the int data type to handle all integer values. The query arises here. In Python, what is the maximum value that the variable can hold? Take a look at the following example.

    Example –

    
    
    1. # A Python program to display that we can store  
    2. # large numbers in Python  
    3.   
    4. a = 10000000000000000000000000000000000000000000  
    5. a = a + 1  
    6. print(type(a))  
    7. print (a)  

    Output:<class ‘int’> 10000000000000000000000000000000000000000001

    As we can find in the above model, we assigned a large whole number worth to variable x and really look at its sort. It printed class <int> not long int. As a result, the number of bits is not limited, and we are free to use all of our memory.

    There is no special data type for storing larger numbers in Python.

    Print Single and Numerous Factors in Python

    We can print numerous factors inside the single print explanation. The examples of single and multiple printing values are provided below.

    Example – 1 (Printing Single Variable)

    # printing single value   
    
    a = 5  
    
    print(a)  
    
    print((a))

    Output:5 5

    Example – 2 (Printing Multiple Variables)

    
    
    1. a = 5  
    2. b = 6  
    3. # printing multiple variables  
    4. print(a,b)  
    5. # separate the variables by the comma  
    6. Print(1, 2, 3, 4, 5, 6, 7, 8) 

    Output:5 6 1 2 3 4 5 6 7 8

    Basic Fundamentals:

    This section contains the fundamentals of Python, such as:

    i)Tokens and their types.

    ii) Comments

    a)Tokens:

    • The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
    • The token is the smallest unit inside the given program.

    There are following tokens in Python:

    • Keywords.
    • Identifiers.
    • Literals.
    • Operators.
  • First Python Program

    In this Section, we will discuss the basic syntax of Python, we will run a simple program to print Hello World on the console.

    Python provides us the two ways to run a program:

    • Using Interactive interpreter prompt
    • Using a script file

    Let’s discuss each one of them in detail.

    Interactive interpreter prompt

    Python provides us the feature to execute the Python statement one by one at the interactive prompt. It is preferable in the case where we are concerned about the output of each line of our Python program.

    To open the interactive mode, open the terminal (or command prompt) and type python (python3 in case if you have Python2 and Python3 both installed on your system).

    It will open the following prompt where we can execute the Python statement and check their impact on the console.

    First Python Program

    After writing the print statement, press the Enter key.

    First Python Program

    Here, we get the message “Hello World !” printed on the console.

    Using a script file (Script Mode Programming)

    The interpreter prompt is best to run the single-line statements of the code. However, we cannot write the code every-time on the terminal. It is not suitable to write multiple lines of code.

    Using the script mode, we can write multiple lines code into a file which can be executed later. For this purpose, we need to open an editor like notepad, create a file named and save it with .py extension, which stands for “Python”. Now, we will implement the above example using the script mode.

    1. print (“hello world”); #here, we have used print() function to print the message on the console.    

    To run this file named as first.py, we need to run the following command on the terminal.

    First Python Program

    Step – 1: Open the Python interactive shell, and click “File” then choose “New”, it will open a new blank script in which we can write our code.

    First Python Program

    Step -2: Now, write the code and press “Ctrl+S” to save the file.

    First Python Program

    Step – 3: After saving the code, we can run it by clicking “Run” or “Run Module”. It will display the output to the shell.

    First Python Program

    The output will be shown as follows.

    First Python Program

    Step – 4: Apart from that, we can also run the file using the operating system terminal. But, we should be aware of the path of the directory where we have saved our file.

    • Open the command line prompt and navigate to the directory.
    First Python Program
    • We need to type the python keyword, followed by the file name and hit enter to run the Python file.
    First Python Program

    Multi-line Statements

    Multi-line statements are written into the notepad like an editor and saved it with .py extension. In the following example, we have defined the execution of the multiple code lines using the Python script.

    Code:

    1. name = “Andrew Venis”  
    2. branch = “Computer Science”  
    3. age = “25”  
    4. print(“My name is: “, name, )  
    5. print(“My age is: “, age)  

    Script File:

    First Python Program
    First Python Program

    Pros and Cons of Script Mode

    The script mode has few advantages and disadvantages as well. Let’s understand the following advantages of running code in script mode.

    • We can run multiple lines of code.
    • Debugging is easy in script mode.
    • It is appropriate for beginners and also for experts.

    Let’s see the disadvantages of the script mode.

    • We have to save the code every time if we make any change in the code.
    • It can be tedious when we run a single or a few lines of code.

    Get Started with PyCharm

    In our first program, we have used gedit on our CentOS as an editor. On Windows, we have an alternative like notepad or notepad++ to edit the code. However, these editors are not used as IDE for python since they are unable to show the syntax related suggestions.

    JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the python programs.

    PyCharm installation

    As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed on a variety of the operating systems. In this section of the tutorial, we will cover the installation process of PyCharm on Windows, MacOSCentOS, and Ubuntu.

    Windows

    Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating system, visit the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to download the executable installer. Double click the installer (.exe) file and install PyCharm by clicking next at each step.

    To create a first program to Pycharm follows the following step.

    Step – 1. Open Pycharm editor. Click on “Create New Project” option to create new project.

    First Python Program

    Step – 2. Select a location to save the project.

    1. We can save the newly created project at desired memory location or can keep file location as it is but atleast change the project default name untitled to “FirstProject” or something meaningful.
    2. Pycharm automatically found the installed Python interpreter.
    3. After change the name click on the “Create” Button.
    First Python Program

    Step – 3. Click on “File” menu and select “New”. By clicking “New” option it will show various file formats. Select the “Python File”.

    First Python Program

    Step – 4. Now type the name of the Python file and click on “OK”. We have written the “FirstProgram”.

    First Python Program

    Step – 5. Now type the first program – print(“Hello World”) then click on the “Run” menu to run program.

    First Python Program

    Step – 6. The output will appear at the bottom of the screen.

    First Python Program

    Basic Syntax of Python

    Indentation and Comment in Python

    Indentation is the most significant concept of the Python programming language. Improper use of indentation will end up “IndentationError” in our code.

    Indentation is nothing but adding whitespaces before the statement when it is needed. Without indentation Python doesn’t know which statement to be executed to next. Indentation also defines which statements belong to which block. If there is no indentation or improper indentation, it will display “IndentationError” and interrupt our code.

    First Python Program

    Python indentation defines the particular group of statements belongs to the particular block. The programming languages such as CC++java use the curly braces {} to define code blocks.

    In Python, statements that are the same level to the right belong to the same block. We can use four whitespaces to define indentation. Let’s see the following lines of code.

    Example –

    list1 = [1, 2, 3, 4, 5]  
    
    for i in list1:  
    
        print(i)  
    
        if i==4:  
    
           break  
    
    print("End of for loop")

    Output:1 2 3 4 End of for loop

    Explanation:

    In the above code, for loop has a code blocks and if the statement has its code block inside for loop. Both indented with four whitespaces. The last print() statement is not indented; that’s means it doesn’t belong to for loop.

    Comments in Python

    Comments are essential for defining the code and help us and other to understand the code. By looking the comment, we can easily understand the intention of every line that we have written in code. We can also find the error very easily, fix them, and use in other applications.

    In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores the lines followed by a hash character. A good programmer always uses the comments to make code under stable. Let’s see the following example of a comment.

    1. name  = “Thomas”   # Assigning string value to the name variable   

    We can add comment in each line of the Python code.

    Fees = 10000      # defining course fees is 10000  
    
    Fees = 20000      # defining course fees is 20000

    It is good idea to add code in any line of the code section of code whose purpose is not obvious. This is a best practice to learn while doing the coding.

    Types of Comment

    Python provides the facility to write comments in two ways- single line comment and multi-line comment.

    Single-Line Comment – Single-Line comment starts with the hash # character followed by text for further explanation.

    # defining the marks of a student   
    
    Marks = 90

    We can also write a comment next to a code statement. Consider the following example.

    Name = "James"   # the name of a student is James  
    
    Marks = 90            # defining student's marks  
    
    Branch = "Computer Science"   # defining student branch

    Multi-Line Comments – Python doesn’t have explicit support for multi-line comments but we can use hash # character to the multiple lines. For example –

    # we are defining for loop  
    
    # To iterate the given list.  
    
    # run this code.

    We can also use another way.

    " " "   
    
    This is an example  
    
    Of multi-line comment  
    
    Using triple-quotes   
    
    " " "

    This is the basic introduction of the comments. Visit our Python Comment tutorial to learn it in detail.

    Python Identifiers

    Python identifiers refer to a name used to identify a variable, function, module, class, module or other objects. There are few rules to follow while naming the Python Variable.

    • A variable name must start with either an English letter or underscore (_).
    • A variable name cannot start with the number.
    • Special characters are not allowed in the variable name.
    • The variable’s name is case sensitive.

    Let’s understand the following example.

    Example –

    number = 10  
    
    print(num)  
    
      
    
    _a = 100  
    
    print(_a)  
    
      
    
    x_y = 1000  
    
    print(x_y)

    Output:10 100 1000

    We have defined the basic syntax of the Python programming language. We must be familiar with the core concept of any programming languages. Once we memorize the concepts as mentioned above. The journey of learning Python will become easier.

  • How to Install Python

    Python is a popular high-level, general-use programming language. Python is a programming language that enables rapid development as well as more effective system integration. Python has two main different versions: Python 2 and Python 3. Both are really different.

    Python develops new versions with changes periodically and releases them according to version numbers. Python is currently at version 3.11.3.

    Python is much simpler to learn and programme in. Any plain text editor, such as notepad or notepad++, may be used to create Python programs. To make it easier to create these routines, one may also utilise an online IDE for Python or even install one on their machine. IDEs offer a variety of tools including a user-friendly code editor, the debugger, compiler, etc.

    One has to have Python installed on their system in order to start creating Python code and carrying out many fascinating and helpful procedures. The first step in learning how to programming in Python is to install or update Python on your computer. There are several ways to install Python: you may use a package manager, get official versions from Python.org, or install specialised versions for embedded devices, scientific computing, and the Internet of Things.

    In order to become Python developer, the first step is to learn how to install or update Python on a local machine or computer. In this tutorial, we will discuss the installation of Python on various operating systems.

    Installation on Windows

    Visit the link https://www.python.org to download the latest release of Python. In this process, we will install Python 3.11.3 on our Windows operating system. When we click on the above link, it will bring us the following page.

    Python Environment Set-up

    Step – 1: Select the Python’s version to download.

    Click on the download button to download the exe file of Python.

    Python Environment Set-up

    If in case you want to download the specific version of Python. Then, you can scroll down further below to see different versions from 2 and 3 respectively. Click on download button right next to the version number you want to download.

    Python Environment Set-up

    Step – 2: Click on the Install Now

    Double-click the executable file, which is downloaded.

    Python Environment Set-up

    The following window will open. Click on the Add Path check box, it will set the Python path automatically.

    Now, Select Customize installation and proceed. We can also click on the customize installation to choose desired location and features. Other important thing is install launcher for the all user must be checked.

    Here, under the advanced options, click on the checkboxes of ” Install Python 3.11 for all users “, which is previously not checked in. This will checks the other option ” Precompile standard library ” automatically. And the location of the installation will also be changed. We can change it later, so we leave the install location default. Then, click on the install button to finally install.

    Python Environment Set-up

    Step – 3 Installation in Process

    Python Environment Set-up

    The set up is in progress. All the python libraries, packages, and other python default files will be installed in our system. Once the installation is successful, the following page will appear saying ” Setup was successful “.

    Python Environment Set-up

    Step – 4: Verifying the Python Installation

    To verify whether the python is installed or not in our system, we have to do the following.

    • Go to “Start” button, and search ” cmd “.
    • Then type, ” python – – version “.
    • If python is successfully installed, then we can see the version of the python installed.
    • If not installed, then it will print the error as ” ‘python’ is not recognized as an internal or external command, operable program or batch file. “.
    Python Environment Set-up

    We are ready to work with the Python.

    Step – 5: Opening idle

    Now, to work on our first python program, we will go the interactive interpreter prompt(idle). To open this, go to “Start” and type idle. Then, click on open to start working on idle.

    Python Environment Set-up
  • Python Applications

    Python is known for its general-purpose nature that makes it applicable in almost every domain of software development. Python makes its presence in every emerging field. It is the fastest-growing programming language and can develop any application.

    Here, we are specifying application areas where Python can be applied.

    Python Applications

    1) Web Applications

    We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python provides many useful frameworks, and these are given below:

    • Django and Pyramid framework(Use for heavy applications)
    • Flask and Bottle (Micro-framework)
    • Plone and Django CMS (Advance Content management)

    2) Desktop GUI Applications

    The GUI stands for the Graphical User Interface, which provides a smooth interaction to any application. Python provides a Tk GUI library to develop a user interface. Some popular GUI libraries are given below.

    • Tkinter or Tk
    • wxWidgetM
    • Kivy (used for writing multitouch applications )
    • PyQt or Pyside

    3) Console-based Application

    Console-based applications run from the command-line or shell. These applications are computer program which are used commands to execute. This kind of application was more popular in the old generation of computers. Python can develop this kind of application very effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for the command-line applications.

    Python provides many free library or module which helps to build the command-line apps. The necessary IO libraries are used to read and write. It helps to parse argument and create console help text out-of-the-box. There are also advance libraries that can develop independent console apps.

    4) Software Development

    Python is useful for the software development process. It works as a support language and can be used to build control and management, testing, etc.

    • SCons is used to build control.
    • Buildbot and Apache Gumps are used for automated continuous compilation and testing.
    • Round or Trac for bug tracking and project management.

    5) Scientific and Numeric

    This is the era of Artificial intelligence where the machine can perform the task the same as the human. Python language is the most suitable language for Artificial intelligence or machine learning. It consists of many scientific and mathematical libraries, which makes easy to solve complex calculations.

    Implementing machine learning algorithms require complex mathematical calculation. Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some basic knowledge of Python, you need to import libraries on the top of the code. Few popular frameworks of machine libraries are given below.

    • SciPy
    • Scikit-learn
    • NumPy
    • Pandas
    • Matplotlib

    6) Business Applications

    Business Applications differ from standard applications. E-commerce and ERP are an example of a business application. This kind of application requires extensively, scalability and readability, and Python provides all these features.

    Oddo is an example of the all-in-one Python-based application which offers a range of business applications. Python provides a Tryton platform which is used to develop the business application.

    7) Audio or Video-based Applications

    Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The few multimedia libraries are given below.

    • Gstreamer
    • Pyglet
    • QT Phonon

    8) 3D CAD Applications

    The CAD (Computer-aided design) is used to design engineering related architecture. It is used to develop the 3D representation of a part of a system. Python can create a 3D CAD application by using the following functionalities.

    • Fandango (Popular )
    • CAMVOX
    • HeeksCNC
    • AnyCAD
    • RCAM

    9) Enterprise Applications

    Python can be used to create applications that can be used within an Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

    10) Image Processing Application

    Python contains many libraries that are used to work with the image. The image can be manipulated according to our requirements. Some libraries of image processing are given below.

    • OpenCV
    • Pillow
    • SimpleITK

    In this topic, we have described all types of applications where Python plays an essential role in the development of these applications. In the next tutorial, we will learn more concepts about Python.

  • Python History and Versions

    • Python laid its foundation in the late 1980s.
    • The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in Netherland.
    • In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.
    • In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
    • Python 2.0 added new features such as list comprehensions, garbage collection systems.
    • On December 3, 2008, Python 3.0 (also called “Py3K”) was released. It was designed to rectify the fundamental flaw of the language.
    • ABC programming language is said to be the predecessor of Python language, which was capable of Exception Handling and interfacing with the Amoeba Operating System.
    • The following programming languages influence Python:
      • ABC language.
      • Modula-3
    • Why the Name Python?
    • There is a fact behind choosing the name PythonGuido van Rossum was reading the script of a popular BBC comedy series “Monty Python’s Flying Circus“. It was late on-air 1970s.
    • Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select naming Python after the “Monty Python’s Flying Circus” for their newly created programming language.
    • The comedy series was creative and well random. It talks about everything. Thus it is slow and unpredictable, which made it very interesting.
    • Python is also versatile and widely used in every technical field, such as Machine LearningArtificial Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.
    • Python Version List
    • Python programming language is being updated regularly with new features and supports. There are lots of update in Python versions, started from 1994 to current release.
    • A list of Python versions with its released date is given below.
    • Tips to Keep in Mind While Learning Python
    • The most common question asked by the beginners – “What is the best way to learn Python”? It is the initial and relevant question because first step in learning any programming language is to know how to learn.
    • The proper way of learning will help us to learn fast and become a good Python developer.
    • In this section, we will discuss various tips that we should keep in mind while learning Python.
    • 1. Make it Clear Why We Want to Learn
    • The goal should be clear before learning the Python. Python is an easy, a vast language as well. It includes numbers of libraries, modules, in-built functions and data structures. If the goal is unclear then it will be a boring and monotonous journey of learning Python. Without any clear goal, you perhaps won’t make it done.
    • So, first figure out the motivation behind learning, which can anything be such as knowing something new, develop projects using Python, switch to Python, etc. Below are the general areas where Python is widely used. Pick any of them.
    • Data Analysis and Processing
    • Artificial Intelligence
    • Games
    • Hardware/Sensor/Robots
    • Desktop Applications
    • Choose any one or two areas according to your interest and start the journey towards learning Python.
    • 2. Learn the Basic Syntax
    • It is the most essential and basic step to learn the syntax of the Python programming language. We have to learn the basic syntax before dive deeper into learning it. As we have discussed in our earlier tutorial, Python is easy to learn and has a simple syntax. It doesn’t use semicolon and brackets. Its syntax is like the English language.
    • So it will take minimum amount of time to learning its syntax. Once we get its syntax properly, further learning will be easier and quicker getting to work on projects.
    • Note – Learn Python 3, not Python 2.7, because the industry no longer uses it. Our Python tutorial is based on its latest version Python 3.
    • 3. Write Code by Own
    • Writing the code is the most effective and robust way to learn Python. First, try to write code on paper and run in mind (Dry Run) then move to the system. Writing code on paper will help us get familiar quickly with the syntax and the concept store in the deep memory. While writing the code, try to use proper functions and suitable variables names.
    • There are many editors available for Python programming which highlights the syntax related issue automatically. So we don’t need to pay lot of attention of these mistakes.
    • 4. Keep Practicing
    • The next important step is to do the practice. It needs to implementing the Python concepts through the code. We should be consistence to our daily coding practice.
    • Consistency is the key of success in any aspect of life not only in programming. Writing code daily will help to develop muscle memory.
    • We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It may seem hard but muscle memory plays large part in programing. It will take us ahead from those who believe only the reading concept of Python is sufficient.
    • 5. Make Notes as Needed
    • Creating notes by own is an excellent method to learn the concepts and syntax of Python. It will establish stability and focus that helps you become a Python developer. Make brief and concise notes with relevant information and include appropriate examples of the subject concerned.
    • Maintain own notes are also helped to learn fast. A study published in Psychological Science that –
    • The students who were taking longhand notes in the studies were forced to be more selective — because you can’t write as fast as you can type.
    • 6. Discuss Concepts with Other
    • Coding seems to be solitary activity, but we can enhance our skills by interacting with the others. We should discuss our doubts to the expert or friends who are learning Python. This habit will help to get additional information, tips and tricks, and solution of coding problems. One of the best advantages of Python, it has a great community. Therefore, we can also learn from passionate Python enthusiasts.
    • 7. Do small Projects
    • After understanding Python’s basic concept, a beginner should try to work on small projects. It will help to understand Python more deeply and become more component in it. Theoretical knowledge is not enough to get command over the Python language. These projects can be anything as long as they teach you something. You can start with the small projects such as calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer management system, etc.
    • Once you get handy with a small project, you can easily shift toward your interesting domain (Machine Learning, Web Development, etc.).
    • 8. Teach Others
    • There is a famous saying that “If you want to learn something then you should teach other”. It is also true in case of learning Python. Share your information to other students via creating blog posts, recording videos or taking classes in local training center. It will help us to enhance the understanding of Python and explore the unseen loopholes in your knowledge. If you don’t want to do all these, join the online forum and post your answers on Python related questions.
    • 9. Explore Libraries and Frameworks
    • Python consists of vast libraries and various frameworks. After getting familiar with Python’s basic concepts, the next step is to explore the Python libraries. Libraries are essential to work with the domain specific projects. In the following section, we describe the brief introduction of the main libraries.
    • TensorFlow – It is an artificial intelligence library which allows us to create large scale AI based projects.
    • Django – It is an open source framework that allows us to develop web applications. It is easy, flexible, and simple to manage.
    • Flask – It is also an open source web framework. It is used to develop lightweight web applications.
    • Pandas – It is a Python library which is used to perform scientific computations.
    • Keras – It is an open source library, which is used to work around the neural network.
    • There are many libraries in Python. Above, we have mentioned a few of them.
    • 10. Contribute to Open Source
    • As we know, Python is an open source language that means it is freely available for everyone. We can also contribute to Python online community to enhance our knowledge. Contributing to open source projects is the best way to explore own knowledge. We also receive the feedback, comments or suggestions for work that we submitted. The feedback will enable the best practices for Python programming and help us to become a good Python developer.
    • Usage of Python
    • Python is a general purpose, open source, high-level programming language and also provides number of libraries and frameworks. Python has gained popularity because of its simplicity, easy syntax and user-friendly environment. The usage of Python as follows.
    • Desktop Applications
    • Web Applications
    • Data Science
    • Artificial Intelligence
    • Machine Learning
    • Scientific Computing
    • Robotics
    • Internet of Things (IoT)
    • Gaming
    • Mobile Apps
    • Data Analysis and Preprocessing
    • In the next topic, we will discuss the Python Application, where we have defined Python’s usage in detail.
  • Python Features

    Python provides many useful features which make it popular and valuable from the other programming languages. It supports object-oriented programming, procedural programming approaches and provides dynamic memory allocation. We have listed below a few essential features.

    1) Easy to Learn and Use

    Python is easy to learn as compared to other programming languages. Its syntax is straightforward and much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended programming language for beginners.

    2) Expressive Language

    Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type print(“Hello World”). It will take only one line to execute, while Java or C takes multiple lines.

    3) Interpreted Language

    Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being interpreted language, it makes debugging easy and portable.

    4) Cross-platform Language

    Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop the software for several competing platforms by writing a program only once.

    5) Free and Open Source

    Python is freely available for everyone. It is freely available on its official website www.python.org. It has a large community across the world that is dedicatedly working towards make new python modules and functions. Anyone can contribute to the Python community. The open-source means, “Anyone can download its source code without paying any penny.”

    6) Object-Oriented Language

    Python supports object-oriented language and concepts of classes and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to programmer to write reusable code and develop applications in less code.

    7) Extensible

    It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our Python code. It converts the program into byte code, and any platform can use that byte code.

    8) Large Standard Library

    It provides a vast range of libraries for the various fields such as machine learning, web developer, and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.

    9) GUI Programming Support

    Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.

    10) Integrated

    It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++ Java. It makes easy to debug the code.

    11. Embeddable

    The code of the other programming language can use in the Python source code. We can use Python source code in another programming language as well. It can embed other language into our code.

    12. Dynamic Memory Allocation

    In Python, we don’t need to specify the data-type of the variable. When we assign some value to the variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15 to x, then we don’t need to write int x = 15. Just write x = 15.