Author: Saim Khalid

  • Python break statement

    The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.

    The break is commonly used in the cases where we need to break the loop for a given condition. The syntax of the break statement in Python is given below.

    Syntax:

    #loop statements  
    
    break;

    Example 1 : break statement with for loop

    Code

    # break statement example  
    
    my_list = [1, 2, 3, 4]  
    
    count = 1  
    
    for item in my_list:  
    
        if item == 4:  
    
            print("Item matched")  
    
            count += 1  
    
            break  
    
    print("Found at location", count)

    Output:Item matched Found at location 2

    In the above example, a list is iterated using a for loop. When the item is matched with value 4, the break statement is executed, and the loop terminates. Then the count is printed by locating the item.

    Example 2 : Breaking out of a loop early

    Code

    # break statement example  
    
    my_str = "python"  
    
    for char in my_str:  
    
        if char == 'o':  
    
            break  
    
        print(char)

    Output:p y t h

    When the character is found in the list of characters, break starts executing, and iterating stops immediately. Then the next line of the print statement is printed.

    Example 3: break statement with while loop

    Code

    # break statement example  
    
    i = 0;    
    
    while 1:    
    
        print(i," ",end=""),    
    
        i=i+1;    
    
        if i == 10:    
    
            break;    
    
    print("came out of while loop");

    Output:0 1 2 3 4 5 6 7 8 9 came out of while loop

    It is the same as the above programs. The while loop is initialised to True, which is an infinite loop. When the value is 10 and the condition becomes true, the break statement will be executed and jump to the later print statement by terminating the while loop.

    Example 4 : break statement with nested loops

    Code

    # break statement example  
    
    n = 2  
    
    while True:  
    
        i = 1  
    
        while i <= 10:  
    
            print("%d X %d = %d\n" % (n, i, n * i))  
    
            i += 1  
    
        choice = int(input("Do you want to continue printing the table? Press 0 for no: "))  
    
        if choice == 0:  
    
            print("Exiting the program...")  
    
            break  
    
        n += 1  
    
    print("Program finished successfully.")

    Output:2 X 1 = 2 2 X 2 = 4 2 X 3 = 6 2 X 4 = 8 2 X 5 = 10 2 X 6 = 12 2 X 7 = 14 2 X 8 = 16 2 X 9 = 18 2 X 10 = 20 Do you want to continue printing the table? Press 0 for no: 1 3 X 1 = 3 3 X 2 = 6 3 X 3 = 9 3 X 4 = 12 3 X 5 = 15 3 X 6 = 18 3 X 7 = 21 3 X 8 = 24 3 X 9 = 27 3 X 10 = 30 Do you want to continue printing the table? Press 0 for no: 0 Exiting the program… Program finished successfully.

    There are two nested loops in the above program. Inner loop and outer loop The inner loop is responsible for printing the multiplication table, whereas the outer loop is responsible for incrementing the n value. When the inner loop completes execution, the user will have to continue printing. When 0 is entered, the break statement finally executes, and the nested loop is terminated.


  • Python While Loops

    In coding, loops are designed to execute a specified code block repeatedly. We’ll learn how to construct a while loop in Python, the syntax of a while loop, loop controls like break and continue, and other exercises in this tutorial.

    Introduction of Python While Loop

    In this article, we are discussing while loops in Python. The Python while loop iteration of a code block is executed as long as the given Condition, i.e., conditional_expression, is true.

    If we don’t know how many times we’ll execute the iteration ahead of time, we can write an indefinite loop.

    Syntax of Python While Loop

    Now, here we discuss the syntax of the Python while loop. The syntax is given below –

    Statement  
    
    while Condition:  
    
            Statement

    The given condition, i.e., conditional_expression, is evaluated initially in the Python while loop. Then, if the conditional expression gives a boolean value True, the while loop statements are executed. The conditional expression is verified again when the complete code block is executed. This procedure repeatedly occurs until the conditional expression returns the boolean value False.

    • The statements of the Python while loop are dictated by indentation.
    • The code block begins when a statement is indented & ends with the very first unindented statement.
    • Any non-zero number in Python is interpreted as boolean True. False is interpreted as None and 0.

    Example

    Now we give some examples of while Loop in Python. The examples are given in below –

    Program code 1:

    Now we give code examples of while loops in Python for printing numbers from 1 to 10. The code is given below –

    i=1  
    
    while i<=10:  
    
        print(i, end=' ')  
    
        i+=1

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -1 2 3 4 5 6 7 8 9 10

    Program Code 2:

    Now we give code examples of while loops in Python for Printing those numbers divisible by either 5 or 7 within 1 to 50 using a while loop. The code is given below –

    i=1  
    
    while i<51:  
    
        if i%5 == 0 or i%7==0 :  
    
            print(i, end=' ')  
    
        i+=1

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50

    Program Code:

    Now we give code examples of while loops in Python, the sum of squares of the first 15 natural numbers using a while loop. The code is given below –

    # Python program example to show the use of while loop   
    
      
    
    num = 15  
    
      
    
    # initializing summation and a counter for iteration  
    
    summation = 0  
    
    c = 1  
    
      
    
    while c <= num: # specifying the condition of the loop  
    
        # begining the code block  
    
        summation = c**2 + summation  
    
        c = c + 1    # incrementing the counter  
    
      
    
    # print the final sum  
    
    print("The sum of squares is", summation)

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The sum of squares is 1240

    Provided that our counter parameter i gives boolean true for the condition, i less than or equal to num, the loop repeatedly executes the code block i number of times.

    Next is a crucial point (which is mostly forgotten). We have to increment the counter parameter’s value in the loop’s statements. If we don’t, our while loop will execute itself indefinitely (a never-ending loop).

    Finally, we print the result using the print statement.

    Exercises of Python While Loop

    Prime Numbers and Python While Loop

    Using a while loop, we will construct a Python program to verify if the given integer is a prime number or not.

    Program Code:

    Now we give code examples of while loops in Python for a number is Prime number or not. The code is given below –

    num = [34, 12, 54, 23, 75, 34, 11]    
    
      
    
    def prime_number(number):  
    
        condition = 0  
    
        iteration = 2  
    
        while iteration <= number / 2:  
    
            if number % iteration == 0:  
    
                condition = 1  
    
                break  
    
            iteration = iteration + 1  
    
      
    
        if condition == 0:  
    
            print(f"{number} is a PRIME number")  
    
        else:  
    
            print(f"{number} is not a PRIME number")  
    
    for i in num:  
    
        prime_number(i)

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -34 is not a PRIME number 12 is not a PRIME number 54 is not a PRIME number 23 is a PRIME number 75 is not a PRIME number 34 is not a PRIME number 11 is a PRIME number

    2. Armstrong and Python While Loop

    We will construct a Python program using a while loop to verify whether the given integer is an Armstrong number.

    Program Code:

    Now we give code examples of while loops in Python for a number is Armstrong number or not. The code is given below –

    n = int(input())  
    
    n1=str(n)  
    
    l=len(n1)  
    
    temp=n  
    
    s=0  
    
    while n!=0:  
    
        r=n%10  
    
        s=s+(r**1)  
    
        n=n//10  
    
    if s==temp:  
    
        print("It is an Armstrong number")  
    
    else:  
    
        print("It is not an Armstrong number ")

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -342 It is not an Armstrong number

    Multiplication Table using While Loop

    In this example, we will use the while loop for printing the multiplication table of a given number.

    Program Code:

    In this example, we will use the while loop for printing the multiplication table of a given number. The code is given below –

    num = 21        
    
    counter = 1      
    
    # we will use a while loop for iterating 10 times for the multiplication table        
    
    print("The Multiplication Table of: ", num)      
    
    while counter <= 10: # specifying the condition  
    
        ans = num * counter      
    
        print (num, 'x', counter, '=', ans)      
    
        counter += 1 # expression to increment the counter

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The Multiplication Table of: 21 21 x 1 = 21 21 x 2 = 42 21 x 3 = 63 21 x 4 = 84 21 x 5 = 105 21 x 6 = 126 21 x 7 = 147 21 x 8 = 168 21 x 9 = 189 21 x 10 = 210

    Python While Loop with List

    Program Code 1:

    Now we give code examples of while loops in Python for square every number of a list. The code is given below –

    # Python program to square every number of a list    
    
    # initializing a list    
    
    list_ = [3, 5, 1, 4, 6]    
    
    squares = []    
    
    # programing a while loop     
    
    while list_: # until list is not empty this expression will give boolean True after that False    
    
        squares.append( (list_.pop())**2)    
    
    #  Print the squares of all numbers.  
    
    print( squares )

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -[36, 16, 1, 25, 9]

    In the preceding example, we execute a while loop over a given list of integers that will repeatedly run if an element in the list is found.

    Program Code 2:

    Now we give code examples of while loops in Python for determine odd and even number from every number of a list. The code is given below –

    list_ = [3, 4, 8, 10, 34, 45, 67,80]        # Initialize the list  
    
    index = 0  
    
    while index < len(list_):  
    
        element = list_[index]  
    
        if element % 2 == 0:  
    
            print('It is an even number')       # Print if the number is even.  
    
        else:  
    
            print('It is an odd number')        # Print if the number is odd.  
    
        index += 1

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -It is an odd number It is an even number It is an even number It is an even number It is an even number It is an odd number It is an odd number It is an even number

    Program Code 3:

    Now we give code examples of while loops in Python for determine the number letters of every word from the given list. The code is given below –

    List_= ['Priya', 'Neha', 'Cow', 'To']  
    
    index = 0  
    
    while index < len(List_):  
    
        element = List_[index]  
    
        print(len(element))  
    
        index += 1

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -5 4 3 2

    Python While Loop Multiple Conditions

    We must recruit logical operators to combine two or more expressions specifying conditions into a single while loop. This instructs Python on collectively analyzing all the given expressions of conditions.

    We can construct a while loop with multiple conditions in this example. We have given two conditions and a and keyword, meaning the Loop will execute the statements until both conditions give Boolean True.

    Program Code:

    Now we give code examples of while loops in Python for multiple condition. The code is given below –

    num1 = 17  
    
    num2 = -12  
    
       
    
    while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop  
    
        num1 -= 2  
    
        num2 += 3  
    
        print( (num1, num2) )

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -(15, -9) (13, -6) (11, -3)

    Let’s look at another example of multiple conditions with an OR operator.

    num1 = 17  
    
    num2 = -12  
    
       
    
    while num1 > 5 or num2 < -5 :  
    
        num1 -= 2  
    
        num2 += 3  
    
        print( (num1, num2) )

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -(15, -9) (13, -6) (11, -3) (9, 0) (7, 3) (5, 6)

    We can also group multiple logical expressions in the while loop, as shown in this example.

    Code

    num1 = 9   
    
    num = 14   
    
    maximum_value = 4  
    
    counter = 0   
    
    while (counter < num1 or counter < num2) and not counter >= maximum_value: # grouping multiple conditions  
    
        print(f"Number of iterations: {counter}")   
    
        counter += 1

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Number of iterations: 0 Number of iterations: 1 Number of iterations: 2 Number of iterations: 3

    Single Statement While Loop

    Similar to the if statement syntax, if our while clause consists of one statement, it may be written on the same line as the while keyword.

    Here is the syntax and example of a one-line while clause –

    # Python program to show how to create a single statement while loop  
    
    counter = 1  
    
    while counter: print('Python While Loops')

    Loop Control Statements

    Now we will discuss the loop control statements in detail. We will see an example of each control statement.

    Continue Statement

    It returns the control of the Python interpreter to the beginning of the loop.

    Code

    # Python program to show how to use continue loop control  
    
      
    
    # Initiating the loop  
    
    for string in "While Loops":  
    
        if string == "o" or string == "i" or string == "e":  
    
             continue  
    
        print('Current Letter:', string)

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

    Output:Current Letter: W Current Letter: h Current Letter: l Current Letter: Current Letter: L Current Letter: p Current Letter: s

    Break Statement

    It stops the execution of the loop when the break statement is reached.

    Code

    # Python program to show how to use the break statement  
    
      
    
    # Initiating the loop  
    
    for string in "Python Loops":  
    
        if string == 'n':  
    
             break  
    
        print('Current Letter: ', string)

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Current Letter: P Current Letter: y Current Letter: t Current Letter: h Current Letter: o

    Pass Statement

    Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.

    Code

    # Python program to show how to use the pass statement    
    
    for a string in "Python Loops":    
    
        pass    
    
    print( 'The Last Letter of given string is:', string)

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

    Output:The Last Letter of given string is: s

  • Python for loop

    Python is a strong, universally applicable prearranging language planned to be easy to comprehend and carry out. It is allowed to get to because it is open-source. In this tutorial, we will learn how to use Python for loops, one of the most fundamental looping instructions in Python programming.

    Introduction to for Loop in Python

    Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and strings. Crossing is the most common way of emphasizing across a series, for loops are used when a section of code needs to be repeated a certain number of times. The for-circle is typically utilized on an iterable item, for example, a rundown or the in-fabricated range capability. In Python, the for Statement runs the code block each time it traverses a series of elements. On the other hand, the “while” Loop is used when a condition needs to be verified after each repetition or when a piece of code needs to be repeated indefinitely. The for Statement is opposed to this Loop.

    Syntax of for Loop

    for value in sequence:  
    
        {loop body}

    The value is the parameter that determines the element’s value within the iterable sequence on each iteration. When a sequence contains expression statements, they are processed first. The first element in the sequence is then assigned to the iterating variable iterating_variable. From that point onward, the planned block is run. Each element in the sequence is assigned to iterating_variable during the statement block until the sequence as a whole is completed. Using indentation, the contents of the Loop are distinguished from the remainder of the program.

    Example of Python for Loop

    Code

    # Code to find the sum of squares of each element of the list using for loop  
    
      
    
    # creating the list of numbers  
    
    numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]  
    
      
    
    # initializing a variable that will store the sum  
    
    sum_ = 0  
    
      
    
    # using for loop to iterate over the list  
    
    for num in numbers:  
    
         
    
    sum_ = sum_ + num ** 2   
    
      
    
    print("The sum of squares is: ", sum_)

    Output:The sum of squares is: 774

    The range() Function

    Since the “range” capability shows up so habitually in for circles, we could erroneously accept the reach as a part of the punctuation of for circle. It’s not: It is a built-in Python method that fulfills the requirement of providing a series for the for expression to run over by following a particular pattern (typically serial integers). Mainly, they can act straight on sequences, so counting is unnecessary. This is a typical novice construct if they originate from a language with distinct loop syntax:

    Code

    my_list = [3, 5, 6, 8, 4]  
    
    for iter_var in range( len( my_list ) ):  
    
        my_list.append(my_list[iter_var] + 2)  
    
    print( my_list )

    Output:[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]

    Iterating by Using Index of Sequence

    Another method of iterating through every item is to use an index offset within the sequence. Here’s a simple illustration:

    Code

    # Code to find the sum of squares of each element of the list using for loop  
    
      
    
    # creating the list of numbers  
    
    numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]  
    
      
    
    # initializing a variable that will store the sum  
    
    sum_ = 0  
    
      
    
    # using for loop to iterate over list  
    
    for num in range( len(numbers) ):  
    
         
    
    sum_ = sum_ + numbers[num] ** 2   
    
      
    
    print("The sum of squares is: ", sum_)

    Output:The sum of squares is: 774

    The len() worked in a technique that profits the complete number of things in the rundown or tuple, and the implicit capability range(), which returns the specific grouping to emphasize over, proved helpful here.

    Using else Statement with for Loop

    A loop expression and an else expression can be connected in Python.

    After the circuit has finished iterating over the list, the else clause is combined with a for Loop.

    The following example demonstrates how to extract students’ marks from the record by combining a for expression with an otherwise statement.

    Code

    # code to print marks of a student from the record  
    
    student_name_1 = 'Itika'  
    
    student_name_2 = 'Parker'  
    
      
    
      
    
    # Creating a dictionary of records of the students  
    
    records = {'Itika': 90, 'Arshia': 92, 'Peter': 46}  
    
    def marks( student_name ):  
    
        for a_student in record: # for loop will iterate over the keys of the dictionary  
    
            if a_student == student_name:  
    
                return records[ a_student ]  
    
                break  
    
        else:  
    
            return f'There is no student of name {student_name} in the records'   
    
              
    
    # giving the function marks() name of two students  
    
    print( f"Marks of {student_name_1} are: ", marks( student_name_1 ) )  
    
    print( f"Marks of {student_name_2} are: ", marks( student_name_2 ) )

    Output:Marks of Itika are: 90 Marks of Parker are: There is no student of name Parker in the records

    Nested Loops

    If we have a piece of content that we need to run various times and, afterward, one more piece of content inside that script that we need to run B several times, we utilize a “settled circle.” While working with an iterable in the rundowns, Python broadly uses these.

    Code

    import random  
    
    numbers = [ ]  
    
    for val in range(0, 11):  
    
        numbers.append( random.randint( 0, 11 ) )  
    
    for num in range( 0, 11 ):  
    
        for i in numbers:  
    
            if num == i:  
    
                print( num, end = " " )

    Output:0 2 4 5 6 7 8 8 9 10

  • Python Loops

    The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time required for checking the condition differ.

    We can run a single statement or set of statements repeatedly using a loop command.

    The following sorts of loops are available in the Python programming language.

    Sr.No.Name of the loopLoop Type & Description
    1While loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
    2For loopThis type of loop executes a code block multiple times and abbreviates the code that manages the loop variable.
    3Nested loopsWe can iterate a loop inside another loop.

    Loop Control Statements

    Statements used to control loops and change the course of iteration are called control statements. All the objects produced within the local scope of the loop are deleted when execution is completed.

    Python provides the following control statements. We will discuss them later in detail.

    Let us quickly go over the definitions of these loop control statements.

    Sr.No.Name of the control statementDescription
    1Break statementThis command terminates the loop’s execution and transfers the program’s control to the statement next to the loop.
    2Continue statementThis command skips the current iteration of the loop. The statements following the continue statement are not executed once the Python interpreter reaches the continue statement.
    3Pass statementThe pass statement is used when a statement is syntactically necessary, but no code is to be executed.

    The for Loop

    Python’s for loop is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.

    Syntax of the for Loop

    for value in sequence:  
    
        { code block }

    In this case, the variable value is used to hold the value of every item present in the sequence before the iteration begins until this particular iteration is completed.

    Loop iterates until the final item of the sequence are reached.

    Code

    # Python program to show how the for loop works  
    
      
    
    # Creating a sequence which is a tuple of numbers  
    
    numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]  
    
      
    
    # variable to store the square of the number  
    
    square = 0  
    
      
    
    # Creating an empty list  
    
    squares = []  
    
      
    
    # Creating a for loop  
    
    for value in numbers:  
    
        square = value ** 2  
    
        squares.append(square)  
    
    print("The list of squares is", squares)

    Output:The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

    Using else Statement with for Loop

    As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete.

    Only if the execution is complete does the else statement comes into play. It won’t be executed if we exit the loop or if an error is thrown.

    Here is a code to better understand if-else statements.

    Code

    # Python program to show how if-else statements work  
    
      
    
    string = "Python Loop"  
    
      
    
    # Initiating a loop  
    
    for s in a string:  
    
        # giving a condition in if block  
    
        if s == "o":  
    
            print("If block")  
    
        # if condition is not satisfied then else block will be executed  
    
        else:  
    
            print(s)

    Output:P y t h If block n L If block If block p

    Now similarly, using else with for loop.

    Syntax:

    
    
    1. for value in sequence:  
    2.      # executes the statements until sequences are exhausted  
    3. else:  
    4.      # executes these statements when for loop is completed  
    # Python program to show how to use else statement with for loop  
    
      
    
    # Creating a sequence  
    
    tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)  
    
      
    
    # Initiating the loop  
    
    for value in tuple_:  
    
        if value % 2 != 0:  
    
            print(value)  
    
    # giving an else statement  
    
    else:  
    
        print("These are the odd numbers present in the tuple")

    Output:3 9 3 9 7 These are the odd numbers present in the tuple

    The range() Function

    With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers).

    We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step size is not specified, it defaults to 1.

    Since it doesn’t create every value it “contains” after we construct it, the range object can be characterized as being “slow.” It does provide in, len, and __getitem__ actions, but it is not an iterator.

    The example that follows will make this clear.

    Code

    # Python program to show the working of range() function  
    
      
    
    print(range(15))  
    
      
    
    print(list(range(15)))  
    
      
    
    print(list(range(4, 9)))  
    
      
    
    print(list(range(5, 25, 4)))

    Output:range(0, 15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [4, 5, 6, 7, 8] [5, 9, 13, 17, 21]

    To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing to iterate through the given sequence by combining it with an iterable’s len() function. Here’s an illustration.

    Code

    # Python program to iterate over a sequence with the help of indexing  
    
      
    
    tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")  
    
      
    
    # iterating over tuple_ using range() function  
    
    for iterator in range(len(tuple_)):  
    
        print(tuple_[iterator].upper())

    Output:PYTHON LOOPS SEQUENCE CONDITION RANGE

    While Loop

    While loops are used in Python to iterate until a specified condition is met. However, the statement in the program that follows the while loop is executed once the condition changes to false.

    Syntax of the while loop is:

    while <condition>:  
    
        { code block }

    All the coding statements that follow a structural command define a code block. These statements are intended with the same number of spaces. Python groups statements together with indentation.
    Code

    # Python program to show how to use a while loop  
    
    counter = 0  
    
    # Initiating the loop  
    
    while counter < 10: # giving the condition  
    
        counter = counter + 3  
    
        print("Python Loops")

    Output:Python Loops Python Loops Python Loops Python Loops

    Using else Statement with while Loops

    As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax.

    Code

    #Python program to show how to use else statement with the while loop  
    
    counter = 0  
    
      
    
    # Iterating through the while loop  
    
    while (counter < 10):      
    
        counter = counter + 3  
    
        print("Python Loops") # Executed untile condition is met  
    
    # Once the condition of while loop gives False this statement will be executed  
    
    else:  
    
        print("Code block inside the else statement")

    Output:Python Loops Python Loops Python Loops Python Loops Code block inside the else statement

    Single statement while Block

    The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where we can write the code block in a single line.

    Code

    # Python program to show how to write a single statement while loop  
    
    counter = 0  
    
    while (count < 3): print("Python Loops")

    Loop Control Statements

    Now we will discuss the loop control statements in detail. We will see an example of each control statement.

    Continue Statement

    It returns the control to the beginning of the loop.

    Code

    # Python program to show how the continue statement works  
    
      
    
    # Initiating the loop  
    
    for string in "Python Loops":  
    
        if string == "o" or string == "p" or string == "t":  
    
             continue  
    
        print('Current Letter:', string)

    Output:Current Letter: P Current Letter: y Current Letter: h Current Letter: n Current Letter: Current Letter: L Current Letter: s

    Break Statement

    It stops the execution of the loop when the break statement is reached.

    Code

    # Python program to show how the break statement works  
    
      
    
    # Initiating the loop  
    
    for string in "Python Loops":  
    
        if string == 'L':  
    
             break  
    
        print('Current Letter: ', string)

    Output:Current Letter: P Current Letter: y Current Letter: t Current Letter: h Current Letter: o Current Letter: n Current Letter:

    Pass Statement

    Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.

    Code

    # Python program to show how the pass statement works  
    
    for a string in "Python Loops":  
    
        pass  
    
    print( 'Last Letter:', string)

    Output:Last Letter: s

  • Python If-else statements

    Decision making is the most important aspect of almost all the programming languages. As the name implies, decision making allows us to run a particular block of code for a particular decision. Here, the decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision making.

    In python, decision making is performed by the following statements.

    StatementDescription
    If StatementThe if statement is used to test a specific condition. If the condition is true, a block of code (if-block) will be executed.
    If – else StatementThe if-else statement is similar to if statement except the fact that, it also provides the block of the code for the false case of the condition to be checked. If the condition provided in the if statement is false, then the else statement will be executed.
    Nested if StatementNested if statements enable us to use if ? else statement inside an outer if statement.

    Indentation in Python

    For the ease of programming and to achieve simplicity, python doesn’t allow the use of parentheses for the block level code. In Python, indentation is used to declare a block. If two statements are at the same indentation level, then they are the part of the same block.

    Generally, four spaces are given to indent the statements which are a typical amount of indentation in python.

    Indentation is the most used part of the python language since it declares the block of code. All the statements of one block are intended at the same level indentation. We will see how the actual indentation takes place in decision making and other stuff in python.

    The if statement

    The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if-block. The condition of if statement can be any valid logical expression which can be either evaluated to true or false.

    Python If-else statements

    The syntax of the if-statement is given below.

    1. if expression:  
    2.     statement  

    Example 1

    # Simple Python program to understand the if statement  
    
    num = int(input("enter the number:"))         
    
    # Here, we are taking an integer num and taking input dynamically  
    
    if num%2 == 0:      
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print("The Given number is an even number")

    Output:enter the number: 10 The Given number is an even number

    Example 2 : Program to print the largest of the three numbers.

    # Simple Python Program to print the largest of the three numbers.  
    
    a = int (input("Enter a: "));    
    
    b = int (input("Enter b: "));    
    
    c = int (input("Enter c: "));    
    
    if a>b and a>c:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print ("From the above three numbers given a is largest");    
    
    if b>a and b>c:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print ("From the above three numbers given b is largest");    
    
    if c>a and c>b:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print ("From the above three numbers given c is largest");

    Output:Enter a: 100 Enter b: 120 Enter c: 130 From the above three numbers given c is largest

    The if-else statement

    The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition.

    If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

    Python If-else statements

    The syntax of the if-else statement is given below.

    if condition:  
    
        #block of statements   
    
    else:   
    
        #another block of statements (else-block)

    Example 1 : Program to check whether a person is eligible to vote or not.

    # Simple Python Program to check whether a person is eligible to vote or not.  
    
    age = int (input("Enter your age: "))    
    
    # Here, we are taking an integer num and taking input dynamically  
    
    if age>=18:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print("You are eligible to vote !!");    
    
    else:    
    
        print("Sorry! you have to wait !!");

    Output:Enter your age: 90 You are eligible to vote !!

    Example 2: Program to check whether a number is even or not.

    # Simple Python Program to check whether a number is even or not.  
    
    num = int(input("enter the number:"))         
    
    # Here, we are taking an integer num and taking input dynamically  
    
    if num%2 == 0:      
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print("The Given number is an even number")    
    
    else:    
    
        print("The Given Number is an odd number")

    Output:enter the number: 10 The Given number is even number

    The elif statement

    The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them. We can have any number of elif statements in our program depending upon our need. However, using elif is optional.

    The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

    The syntax of the elif statement is given below.

    if expression 1:   
    
        # block of statements   
    
      
    
    elif expression 2:   
    
        # block of statements   
    
      
    
    elif expression 3:   
    
        # block of statements   
    
      
    
    else:   
    
        # block of statements
    Python If-else statements

    Example 1

    # Simple Python program to understand elif statement  
    
    number = int(input("Enter the number?"))    
    
    # Here, we are taking an integer number and taking input dynamically  
    
    if number==10:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print("The given number is equals to 10")    
    
    elif number==50:  
    
    # Here, we are checking the condition. If the condition is true, we will enter the block    
    
        print("The given number is equal to 50");    
    
    elif number==100:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
        print("The given number is equal to 100");    
    
    else:    
    
        print("The given number is not equal to 10, 50 or 100");

    Output:Enter the number?15 The given number is not equal to 10, 50 or 100

    Example 2

    # Simple Python program to understand elif statement  
    
    marks = int(input("Enter the marks? "))    
    
    # Here, we are taking an integer marks and taking input dynamically  
    
    if marks > 85 and marks <= 100:  
    
    # Here, we are checking the condition. If the condition is true, we will enter the block    
    
       print("Congrats ! you scored grade A ...")    
    
    elif marks > 60 and marks <= 85:    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
       print("You scored grade B + ...")    
    
    elif marks > 40 and marks <= 60:  
    
    # Here, we are checking the condition. If the condition is true, we will enter the block    
    
       print("You scored grade B ...")    
    
    elif (marks > 30 and marks <= 40):    
    
    # Here, we are checking the condition. If the condition is true, we will enter the block  
    
       print("You scored grade C ...")    
    
    else:    
    
       print("Sorry you are fail ?")

    Output:Enter the marks? 89 Congrats ! you scored grade A …

  • Python Comments

    We’ll study how to write comments in our program in this article. We’ll also learn about single-line comments, multi-line comments, documentation strings, and other Python comments.

    Introduction to Python Comments

    We may wish to describe the code we develop. We might wish to take notes of why a section of script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and sophisticated business logic are typically explained with comments. The Python interpreter overlooks the remarks and solely interprets the script when running a program. Single-line comments, multi-line comments, and documentation strings are the 3 types of comments in Python.

    Advantages of Using Comments

    Our code is more comprehensible when we use comments in it. It assists us in recalling why specific sections of code were created by making the program more understandable.

    Aside from that, we can leverage comments to overlook specific code while evaluating other code sections. This simple technique stops some lines from running or creates a fast pseudo-code for the program.

    Below are some of the most common uses for comments:

    • Readability of the Code
    • Restrict code execution
    • Provide an overview of the program or project metadata
    • To add resources to the code

    Types of Comments in Python

    In Python, there are 3 types of comments. They are described below:

    Single-Line Comments

    Single-line remarks in Python have shown to be effective for providing quick descriptions for parameters, function definitions, and expressions. A single-line comment of Python is the one that has a hashtag # at the beginning of it and continues until the finish of the line. If the comment continues to the next line, add a hashtag to the subsequent line and resume the conversation. Consider the accompanying code snippet, which shows how to use a single line comment:

    Code

    # This code is to show an example of a single-line comment  
    
    print( 'This statement does not have a hashtag before it' )

    Output:This statement does not have a hashtag before it

    The following is the comment:

    1. # This code is to show an example of a single-line comment  

    The Python compiler ignores this line.

    Everything following the # is omitted. As a result, we may put the program mentioned above in one line as follows:

    print( 'This is not a comment' ) # this code is to show an example of a single-line comment  

    Output:This is not a comment

    This program’s output will be identical to the example above. The computer overlooks all content following #.

    Multi-Line Comments

    Python does not provide the facility for multi-line comments. However, there are indeed many ways to create multi-line comments.

    With Multiple Hashtags (#)

    In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line with a (#) before it will be regarded as a single-line comment.

    Code

    # it is a  
    
    # comment  
    
    # extending to multiple lines

    In this case, each line is considered a comment, and they are all omitted.

    Using String Literals

    Because Python overlooks string expressions that aren’t allocated to a variable, we can utilize them as comments.

    Code

    'it is a comment extending to multiple lines'  

    We can observe that on running this code, there will be no output; thus, we utilize the strings inside triple quotes(“””) as multi-line comments.

    Python Docstring

    The strings enclosed in triple quotes that come immediately after the defined function are called Python docstring. It’s designed to link documentation developed for Python modules, methods, classes, and functions together. It’s placed just beneath the function, module, or class to explain what they perform. The docstring is then readily accessible in Python using the __doc__ attribute.

    Code

    # Code to show how we use docstrings in Python  
    
      
    
    def add(x, y):  
    
        """This function adds the values of x and y"""  
    
        return x + y  
    
       
    
    # Displaying the docstring of the add function  
    
    print( add.__doc__ )

    Output:This function adds the values of x and y


  • 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}