Blog

  • Python List

    In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of values or items. Since Python lists are mutable, we can change their elements after forming. The comma (,) and the square brackets [enclose the List’s items] serve as separators.

    Although six Python data types can hold sequences, the List is the most common and reliable form. A list, a type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data formats for sequences.

    Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as Array List in Java and Vector in C++. A list is a collection of items separated by commas and denoted by the symbol [].

    List Declaration

    Code

    
    
    1. # a simple list   
    2. list1 = [1, 2, "Python", "Program", 15.9]      
    3. list2 = ["Amy", "Ryan", "Henry", "Emma"]   
    4.   
    5. # printing the list  
    6. print(list1)  
    7. print(list2)  
    8.   
    9. # printing the type of list  
    10. print(type(list1))  
    11. print(type(list2))  

    Output:[1, 2, ‘Python’, ‘Program’, 15.9] [‘Amy’, ‘Ryan’, ‘Henry’, ‘Emma’] < class ‘ list ‘ > < class ‘ list ‘ >

    Characteristics of Lists

    The characteristics of the List are as follows:

    • The lists are in order.
    • The list element can be accessed via the index.
    • The mutable type of List is
    • The rundowns are changeable sorts.
    • The number of various elements can be stored in a list.

    Ordered List Checking

    Code

    # example  
    
    a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]    
    
    b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]    
    
    a == b

    Output:False

    The indistinguishable components were remembered for the two records; however, the subsequent rundown changed the file position of the fifth component, which is against the rundowns’ planned request. False is returned when the two lists are compared.

    Code

    # example  
    
    a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]    
    
    b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]    
    
    a == b

    Output:True

    Records forever protect the component’s structure. Because of this, it is an arranged collection of things.

    Let’s take a closer look at the list example.

    Code

    # list example in detail  
    
    emp = [ "John", 102, "USA"]       
    
    Dep1 = [ "CS",10]    
    
    Dep2 = [ "IT",11]      
    
    HOD_CS = [ 10,"Mr. Holding"]      
    
    HOD_IT = [11, "Mr. Bewon"]      
    
    print("printing employee data ...")      
    
    print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))      
    
    print("printing departments ...")     
    
    print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0], Dep2[1], Dep2[0], Dep2[1]))      
    
    print("HOD Details ....")      
    
    print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))      
    
    print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))      
    
    print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))

    Output:printing employee data… Name : John, ID: 102, Country: USA printing departments… Department 1: Name: CS, ID: 11 Department 2: Name: IT, ID: 11 HOD Details …. CS HOD Name: Mr. Holding, Id: 10 IT HOD Name: Mr. Bewon, Id: 11 <class ‘ list ‘> <class ‘ list ‘> <class ‘ list ‘> <class ‘ list ‘> <class ‘ list ‘>

    In the preceding illustration, we printed the employee and department-specific details from lists that we had created. To better comprehend the List’s concept, look at the code above.

    List Indexing and Splitting

    The indexing procedure is carried out similarly to string processing. The slice operator [] can be used to get to the List’s components.

    The index ranges from 0 to length -1. The 0th index is where the List’s first element is stored; the 1st index is where the second element is stored, and so on.

    Python List

    We can get the sub-list of the list using the following syntax.

    1. list_varible(start:stop:step)    
    • The beginning indicates the beginning record position of the rundown.
    • The stop signifies the last record position of the rundown.
    • Within a start, the step is used to skip the nth element: stop.

    The start parameter is the initial index, the step is the ending index, and the value of the end parameter is the number of elements that are “stepped” through. The default value for the step is one without a specific value. Inside the resultant Sub List, the same with record start would be available, yet the one with the file finish will not. The first element in a list appears to have an index of zero.

    Consider the following example:

    Code

    list = [1,2,3,4,5,6,7]    
    
    print(list[0])    
    
    print(list[1])    
    
    print(list[2])    
    
    print(list[3])    
    
    # Slicing the elements    
    
    print(list[0:6])    
    
    # By default, the index value is 0 so its starts from the 0th element and go for index -1.    
    
    print(list[:])    
    
    print(list[2:5])    
    
    print(list[1:6:2])

    Output:1 2 3 4 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7] [3, 4, 5] [2, 4, 6]

    In contrast to other programming languages, Python lets you use negative indexing as well. The negative indices are counted from the right. The index -1 represents the final element on the List’s right side, followed by the index -2 for the next member on the left, and so on, until the last element on the left is reached.

    Python List

    Let’s have a look at the following example where we will use negative indexing to access the elements of the list.

    Code

    # negative indexing example  
    
    list = [1,2,3,4,5]    
    
    print(list[-1])    
    
    print(list[-3:])    
    
    print(list[:-1])    
    
    print(list[-3:-1])

    Output:5 [3, 4, 5] [1, 2, 3, 4] [3, 4]

    Negative indexing allows us to obtain an element, as previously mentioned. The rightmost item in the List was returned by the first print statement in the code above. The second print statement returned the sub-list, and so on.

    Updating List Values

    Due to their mutability and the slice and assignment operator’s ability to update their values, lists are Python’s most adaptable data structure. Python’s append() and insert() methods can also add values to a list.

    Consider the following example to update the values inside the List.

    Code

    
    
    1. # updating list values  
    2. list = [1, 2, 3, 4, 5, 6]       
    3. print(list)       
    4. # It will assign value to the value to the second index     
    5. list[2] = 10     
    6. print(list)      
    7. # Adding multiple-element     
    8. list[1:3] = [89, 78]       
    9. print(list)     
    10. # It will add value at the end of the list    
    11. list[-1] = 25    
    12. print(list)

    Output:[1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25]

    The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list.

    Consider the following example to delete the list elements.

    Code

    list = [1, 2, 3, 4, 5, 6]       
    
    print(list)       
    
    # It will assign value to the value to second index     
    
    list[2] = 10     
    
    print(list)      
    
    # Adding multiple element     
    
    list[1:3] = [89, 78]       
    
    print(list)     
    
    # It will add value at the end of the list    
    
    list[-1] = 25    
    
    print(list)

    Output:[1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25]

    Python List Operations

    Repetition
    
    Concatenation
    
    Length
    
    Iteration
    
    Membership

    Let’s see how the list responds to various operators.

    1. Repetition

    The redundancy administrator empowers the rundown components to be rehashed on different occasions.

    Code

    # repetition of list  
    
    # declaring the list  
    
    list1 = [12, 14, 16, 18, 20]  
    
    # repetition operator *  
    
    l = list1 * 2  
    
    print(l)

    Output:[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

    2. Concatenation

    It concatenates the list mentioned on either side of the operator.

    Code

    # concatenation of two lists  
    
    # declaring the lists  
    
    list1 = [12, 14, 16, 18, 20]  
    
    list2 = [9, 10, 32, 54, 86]  
    
    # concatenation operator +  
    
    l = list1 + list2  
    
    print(l)

    Output:[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

    3. Length

    It is used to get the length of the list

    Code

    1. # size of the list  
    2. # declaring the list  
    3. list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]  
    4. # finding length of the list  
    5. len(list1)  

    Output:9

    4. Iteration

    The for loop is used to iterate over the list elements.

    Code

    
    
    1. # iteration of the list  
    2. # declaring the list  
    3. list1 = [12, 14, 16, 39, 40]  
    4. # iterating  
    5. for i in list1:   
    6.     print(i)  

    Output:12 14 16 39 40

    5. Membership

    It returns true if a particular item exists in a particular list otherwise false.

    Code

    # membership of the list  
    
    # declaring the list  
    
    list1 = [100, 200, 300, 400, 500]  
    
    # true will be printed if value exists  
    
    # and false if not  
    
      
    
    print(600 in list1)  
    
    print(700 in list1)  
    
    print(1040 in list1)  
    
      
    
    print(300 in list1)  
    
    print(100 in list1)  
    
    print(500 in list1)

    Output:False False False True True True

    Iterating a List

    A list can be iterated by using a for – in loop. A simple list containing four strings, which can be iterated as follows.

    Code

    
    
    1. # iterating a list  
    2. list = ["John", "David", "James", "Jonathan"]      
    3. for i in list:     
    4.     # The i variable will iterate over the elements of the List and contains each element in each iteration.       
    5.     print(i)  

    Output:John David James Jonathan

    Adding Elements to the List

    The append() function in Python can add a new item to the List. In any case, the annex() capability can enhance the finish of the rundown.

    Consider the accompanying model, where we take the components of the rundown from the client and print the rundown on the control center.

    Code

    
    
    1. #Declaring the empty list    
    2. l =[]    
    3. #Number of elements will be entered by the user      
    4. n = int(input("Enter the number of elements in the list:"))    
    5. # for loop to take the input    
    6. for i in range(0,n):       
    7.     # The input is taken from the user and added to the list as the item    
    8.     l.append(input("Enter the item:"))       
    9. print("printing the list items..")     
    10. # traversal loop to print the list items      
    11. for i in l:     
    12.     print(i, end = "  ")   

    Output:Enter the number of elements in the list:10 Enter the item:32 Enter the item:56 Enter the item:81 Enter the item:2 Enter the item:34 Enter the item:65 Enter the item:09 Enter the item:66 Enter the item:12 Enter the item:18 printing the list items.. 32 56 81 2 34 65 09 66 12 18

    Removing Elements from the List

    The remove() function in Python can remove an element from the List. To comprehend this idea, look at the example that follows.

    Example –

    Code

    list = [0,1,2,3,4]       
    
    print("printing original list: ");      
    
    for i in list:      
    
        print(i,end=" ")      
    
    list.remove(2)      
    
    print("\nprinting the list after the removal of first element...")      
    
    for i in list:      
    
        print(i,end=" ")

    Output:printing original list: 0 1 2 3 4 printing the list after the removal of first element… 0 1 3 4

    Python List Built-in Functions

    Python provides the following built-in functions, which can be used with the lists.

    1. len()
    2. max()
    3. min()

    len( )

    It is used to calculate the length of the list.

    Code

    # size of the list  
    
    # declaring the list  
    
    list1 = [12, 16, 18, 20, 39, 40]  
    
    # finding length of the list  
    
    len(list1)

    Output:6

    Max( )

    It returns the maximum element of the list

    Code

    # maximum of the list  
    
    list1 = [103, 675, 321, 782, 200]  
    
    # large element in the list  
    
    print(max(list1))

    Output:782

    Min( )

    It returns the minimum element of the list

    Code

    
    
    1. # minimum of the list  
    2. list1 = [103, 675, 321, 782, 200]  
    3. # smallest element in the list  
    4. print(min(list1))  

    Output:103

    Let’s have a look at the few list examples.

    Example: 1- Create a program to eliminate the List’s duplicate items.

    Code

    list1 = [1,2,2,3,55,98,65,65,13,29]    
    
    # Declare an empty list that will store unique values    
    
    list2 = []    
    
    for i in list1:    
    
        if i not in list2:    
    
            list2.append(i)    
    
    print(list2)

    Output:[1, 2, 3, 55, 98, 65, 13, 29]

    Example:2- Compose a program to track down the amount of the component in the rundown.

    Code

    list1 = [3,4,5,9,10,12,24]    
    
    sum = 0    
    
    for i in list1:    
    
        sum = sum+i        
    
    print("The sum is:",sum)

    Output:The sum is: 67 In [8]:

    Example: 3- Compose the program to find the rundowns comprise of somewhere around one normal component.

    Code

    
    
    1. list1 = [1,2,3,4,5,6]    
    2. list2 = [7,8,9,2,10]    
    3. for x in list1:    
    4.     for y in list2:    
    5.         if x == y:    
    6.             print("The common element is:",x)  

    Output:The common element is: 2

  • Python String

    Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial, we will discuss the most popular data type in Python, i.e., string.

    Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated character as the combination of the 0’s and 1’s.

    Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.

    In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

    Consider the following example in Python to create a string.

    Syntax:

    str = "Hi Python !"    

    Here, if we check the type of the variable str using a Python script

    1. print(type(str)), then it will print a string (str).    

    In Python, strings are treated as the sequence of characters, which means that Python doesn’t support the character data-type; instead, a single character written as ‘p’ is treated as the string of length 1.

    Creating String in Python

    We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.

    #Using single quotes  
    
    str1 = 'Hello Python'  
    
    print(str1)  
    
    #Using double quotes  
    
    str2 = "Hello Python"  
    
    print(str2)  
    
      
    
    #Using triple quotes  
    
    str3 = '''''Triple quotes are generally used for  
    
        represent the multiline or 
    
        docstring'''   
    
    print(str3)

    Output:Hello Python Hello Python Triple quotes are generally used for represent the multiline or docstring

    Strings indexing and splitting

    Like other languages, the indexing of the Python strings starts from 0. For example, The string “HELLO” is indexed as given in the below figure.

    Python String

    Consider the following example:

    str = "HELLO"  
    
    print(str[0])  
    
    print(str[1])  
    
    print(str[2])  
    
    print(str[3])  
    
    print(str[4])  
    
    # It returns the IndexError because 6th index doesn't exist  
    
    print(str[6])

    Output:H E L L O IndexError: string index out of range

    As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in Python to access the substring from the given string. Consider the following example.

    Python String

    Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = ‘HELLO’ is given, then str[1:3] will always include str[1] = ‘E’, str[2] = ‘L’ and nothing else.

    Consider the following example:

    # Given String  
    
    str = "JAVATPOINT"  
    
    # Start Oth index to end  
    
    print(str[0:])  
    
    # Starts 1th index to 4th index  
    
    print(str[1:5])  
    
    # Starts 2nd index to 3rd index  
    
    print(str[2:4])  
    
    # Starts 0th to 2nd index  
    
    print(str[:3])  
    
    #Starts 4th to 6th index  
    
    print(str[4:7])

    Output:JAVATPOINT AVAT VA JAV TPO

    We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2, and so on. Consider the following image.

    Python String

    Consider the following example

    str = 'JAVATPOINT'  
    
    print(str[-1])  
    
    print(str[-3])  
    
    print(str[-2:])  
    
    print(str[-4:-1])  
    
    print(str[-7:-2])  
    
    # Reversing the given string  
    
    print(str[::-1])  
    
    print(str[-12])

    Output:T I NT OIN ATPOI TNIOPTAVAJ IndexError: string index out of range

    Reassigning Strings

    Updating the content of the strings is as easy as assigning it to a new string. The string object doesn’t support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.

    Consider the following example.

    Example 1

    str = "HELLO"    
    
    str[0] = "h"    
    
    print(str)

    Output:Traceback (most recent call last): File “12.py”, line 2, in <module> str[0] = “h”; TypeError: ‘str’ object does not support item assignment

    However, in example 1, the string str can be assigned completely to a new content as specified in the following example.

    Example 2

    str = "HELLO"    
    
    print(str)    
    
    str = "hello"    
    
    print(str)

    Output:HELLO hello

    Deleting the String

    As we know that strings are immutable. We cannot delete or remove the characters from the string.  But we can delete the entire string using the del keyword.

    str = "Foobrdigital"  
    
    del str[1]

    Output:TypeError: ‘str’ object doesn’t support item deletion

    Now we are deleting entire string.

    str1 = "Foobrdigital"  
    
    del str1  
    
    print(str1)

    Output:NameError: name ‘str1’ is not defined

    String Operators

    OperatorDescription
    +It is known as concatenation operator used to join the strings given either side of the operator.
    *It is known as repetition operator. It concatenates the multiple copies of the same string.
    []It is known as slice operator. It is used to access the sub-strings of a particular string.
    [:]It is known as range slice operator. It is used to access the characters from the specified range.
    inIt is known as membership operator. It returns if a particular sub-string is present in the specified string.
    not inIt is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
    r/RIt is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as “C://python”. To define any string as a raw string, the character r or R is followed by the string.
    %It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python.

    Example

    Consider the following example to understand the real use of Python operators.

    str = "Hello"     
    
    str1 = " world"    
    
    print(str*3) # prints HelloHelloHello    
    
    print(str+str1)# prints Hello world     
    
    print(str[4]) # prints o                
    
    print(str[2:4]); # prints ll                    
    
    print('w' in str) # prints false as w is not present in str    
    
    print('wo' not in str1) # prints false as wo is present in str1.     
    
    print(r'C://python37') # prints C://python37 as it is written    
    
    print("The string str : %s"%(str)) # prints The string str : Hello

    Output:HelloHelloHello Hello world o ll False False C://python37 The string str : Hello

    Python String Formatting

    Escape Sequence

    Let’s suppose we need to write the text as – They said, “Hello what’s going on?”- the given statement can be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-quotes.

    Example

    Consider the following example to understand the real use of Python operators.

    str = "They said, "Hello what's going on?""  
    
    print(str)

    Output:SyntaxError: invalid syntax

    We can use the triple quotes to accomplish this problem but Python provides the escape sequence.

    The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the double quotes.

    Example –

    # using triple quotes  
    
    print('''''They said, "What's there?"''')  
    
      
    
    # escaping single quotes  
    
    print('They said, "What\'s going on?"')  
    
      
    
    # escaping double quotes  
    
    print("They said, \"What's going on?\"")

    Output:They said, “What’s there?” They said, “What’s going on?” They said, “What’s going on?”

    The list of an escape sequence is given below:

    Sr.Escape SequenceDescriptionExample
    1.\newlineIt ignores the new line.print(“Python1 \ Python2 \ Python3”)Output:Python1 Python2 Python3
    2.\\Backslashprint(“\\”)Output:\
    3.\’Single Quotesprint(‘\”)Output:
    4.\\”Double Quotesprint(“\””)Output:
    5.\aASCII Bellprint(“\a”)
    6.\bASCII Backspace(BS)print(“Hello \b World”)Output:Hello World
    7.\fASCII Formfeedprint(“Hello \f World!”) Hello World!
    8.\nASCII Linefeedprint(“Hello \n World!”)Output:Hello World!
    9.\rASCII Carriege Return(CR)print(“Hello \r World!”)Output:World!
    10.\tASCII Horizontal Tabprint(“Hello \t World!”)Output:Hello World!
    11.\vASCII Vertical Tabprint(“Hello \v World!”)Output:Hello World!
    12.\oooCharacter with octal valueprint(“\110\145\154\154\157”)Output: Hello
    13\xHHCharacter with hex value.print(“\x48\x65\x6c\x6c\x6f”)Output:Hello

    Here is the simple example of escape sequence.

    print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")  
    
    print("This is the \n multiline quotes")  
    
    print("This is \x48\x45\x58 representation")

    Output:C:\Users\DEVANSH SHARMA\Python32\Lib This is the multiline quotes This is HEX representation

    We can ignore the escape sequence from the given string by using the raw string. We can do this by writing r or R in front of the string. Consider the following example.

    1. print(r”C:\\Users\\DEVANSH SHARMA\\Python32″)  

    Output:C:\\Users\\DEVANSH SHARMA\\Python32

    The format() method

    The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as the placeholder in the string and replaced by the format() method argument. Let’s have a look at the given an example:

    # Using Curly braces  
    
    print("{} and {} both are the best friend".format("Devansh","Abhishek"))  
    
      
    
    #Positional Argument  
    
    print("{1} and {0} best players ".format("Virat","Rohit"))  
    
      
    
    #Keyword Argument  
    
    print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

    Output:Devansh and Abhishek both are the best friend Rohit and Virat best players James,Peter,Ricky

    Python String Formatting Using % Operator

    Python allows us to use the format specifiers used in C’s printf statement. The format specifiers in Python are treated in the same way as they are treated in C. However, Python provides an additional operator %, which is used as an interface between the format specifiers and their values. In other words, we can say that it binds the format specifiers to the values.

    Consider the following example.

    Integer = 10;    
    
    Float = 1.290    
    
    String = "Devansh"    
    
    print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My value is %s"%(Integer,Float,String))

    Output:Hi I am Integer … My value is 10 Hi I am float … My value is 1.290000 Hi I am string … My value is Devansh


    Python String functions

    Python provides various in-built functions that are used for string handling. Many String fun

    MethodDescription
    capitalize()It capitalizes the first character of the String. This function is deprecated in python3
    casefold()It returns a version of s suitable for case-less comparisons.
    center(width ,fillchar)It returns a space padded string with the original string centred with equal number of left and right spaces.
    count(string,begin,end)It counts the number of occurrences of a substring in a String between begin and end index.
    decode(encoding = ‘UTF8’, errors = ‘strict’)Decodes the string using codec registered for encoding.
    encode()Encode S using the codec registered for encoding. Default encoding is ‘utf-8’.
    endswith(suffix ,begin=0,end=len(string))It returns a Boolean value if the string terminates with given suffix between begin and end.
    expandtabs(tabsize = 8)It defines tabs in string to multiple spaces. The default space value is 8.
    find(substring ,beginIndex, endIndex)It returns the index value of the string where substring is found between begin index and end index.
    format(value)It returns a formatted version of S, using the passed value.
    index(subsring, beginIndex, endIndex)It throws an exception if string is not found. It works same as find() method.
    isalnum()It returns true if the characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise, it returns false.
    isalpha()It returns true if all the characters are alphabets and there is at least one character, otherwise False.
    isdecimal()It returns true if all the characters of the string are decimals.
    isdigit()It returns true if all the characters are digits and there is at least one character, otherwise False.
    isidentifier()It returns true if the string is the valid identifier.
    islower()It returns true if the characters of a string are in lower case, otherwise false.
    isnumeric()It returns true if the string contains only numeric characters.
    isprintable()It returns true if all the characters of s are printable or s is empty, false otherwise.
    isupper()It returns false if characters of a string are in Upper case, otherwise False.
    isspace()It returns true if the characters of a string are white-space, otherwise false.
    istitle()It returns true if the string is titled properly and false otherwise. A title string is the one in which the first character is upper-case whereas the other characters are lower-case.
    isupper()It returns true if all the characters of the string(if exists) is true otherwise it returns false.
    join(seq)It merges the strings representation of the given sequence.
    len(string)It returns the length of a string.
    ljust(width[,fillchar])It returns the space padded strings with the original string left justified to the given width.
    lower()It converts all the characters of a string to Lower case.
    lstrip()It removes all leading whitespaces of a string and can also be used to remove particular character from leading.
    partition()It searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings.
    maketrans()It returns a translation table to be used in translate function.
    replace(old,new[,count])It replaces the old sequence of characters with the new sequence. The max characters are replaced if max is given.
    rfind(str,beg=0,end=len(str))It is similar to find but it traverses the string in backward direction.
    rindex(str,beg=0,end=len(str))It is same as index but it traverses the string in backward direction.
    rjust(width,[,fillchar])Returns a space padded string having original string right justified to the number of characters specified.
    rstrip()It removes all trailing whitespace of a string and can also be used to remove particular character from trailing.
    rsplit(sep=None, maxsplit = -1)It is same as split() but it processes the string from the backward direction. It returns the list of words in the string. If Separator is not specified then the string splits according to the white-space.
    split(str,num=string.count(str))Splits the string according to the delimiter str. The string splits according to the space if the delimiter is not provided. It returns the list of substring concatenated with the delimiter.
    splitlines(num=string.count(‘\n’))It returns the list of strings at each line with newline removed.
    startswith(str,beg=0,end=len(str))It returns a Boolean value if the string starts with given str between begin and end.
    strip([chars])It is used to perform lstrip() and rstrip() on the string.
    swapcase()It inverts case of all characters in a string.
    title()It is used to convert the string into the title-case i.e., The string meEruT will be converted to Meerut.
    translate(table,deletechars = ”)It translates the string according to the translation table passed in the function .
    upper()It converts all the characters of a string to Upper Case.
    zfill(width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
    rpartition()
  • Python Pass Statement

    What is Python’s Pass Statement?

    The pass statement is also known as the null statement. The Python mediator doesn’t overlook a Remark, though a pass proclamation isn’t. As a result, these two Python keywords are distinct.

    We can use the pass statement as a placeholder when unsure of the code to provide. Therefore, the pass only needs to be placed on that line. The pass might be utilized when we wish no code to be executed. We can simply insert a pass in cases where empty code is prohibited, such as in loops, functions, class definitions, and if-else statements.

    Syntax

    Keyword:  
    
        pass

    Ordinarily, we use it as a perspective for what’s to come.

    Let’s say we have an if-else statement or loop that we want to fill in the future but cannot. An empty body for the pass keyword would be grammatically incorrect. A mistake would be shown by the Python translator proposing to occupy the space. As a result, we use the pass statement to create a code block that does nothing.

    An Illustration of the Pass Statement

    Code

    # Python program to show how to use a pass statement in a for loop  
    
    '''''pass acts as a placeholder. We can fill this place later on'''  
    
    sequence = {"Python", "Pass", "Statement", "Placeholder"}  
    
    for value in sequence:  
    
        if value == "Pass":  
    
            pass # leaving an empty if block using the pass keyword  
    
        else:  
    
            print("Not reached pass keyword: ", value)

    Output:Not reached pass keyword: Python Not reached pass keyword: Placeholder Not reached pass keyword: Statement

    The same thing is also possible to create an empty function or a class.

    Code

    # Python program to show how to create an empty function and an empty class  
    
      
    
    # Empty function:  
    
    def empty():  
    
        pass  
    
      
    
    # Empty class  
    
    class Empty:  
    
        pass
  • Python continue Statement

    Python continue keyword is used to skip the remaining statements of the current loop and go to the next iteration. In Python, loops repeat processes on their own in an efficient way. However, there might be occasions when we wish to leave the current loop entirely, skip iteration, or dismiss the condition controlling the loop.

    We use Loop control statements in such cases. The continue keyword is a loop control statement that allows us to change the loop’s control. Both Python while and Python for loops can leverage the continue statements.

    Syntax:

    1. continue  

    Python Continue Statements in for Loop

    Printing numbers from 10 to 20 except 15 can be done using continue statement and for loop. The following code is an example of the above scenario:

    # Python code to show example of continue statement  
    
       
    
    # looping from 10 to 20  
    
    for iterator in range(10, 21):  
    
       
    
        # If iterator is equals to 15, loop will continue to the next iteration  
    
        if iterator == 15:  
    
            continue  
    
        # otherwise printing the value of iterator  
    
        print( iterator )

    Output:10 11 12 13 14 16 17 18 19 20

    Explanation: We will execute a loop from 10 to 20 and test the condition that the iterator is equal to 15. If it equals 15, we’ll employ the continue statement to skip to the following iteration displaying any output; otherwise, the loop will print the result.

    Python Continue Statements in while Loop

    Code

    # Creating a string  
    
    string = "JavaTpoint"  
    
    # initializing an iterator  
    
    iterator = 0  
    
       
    
    # starting a while loop                   
    
    while iterator < len(string):  
    
        # if loop is at letter a it will skip the remaining code and go to next iteration  
    
        if string[iterator] == 'a':    
    
            continue    
    
        # otherwise it will print the letter  
    
        print(string[ iterator ])  
    
        iterator += 1

    Output:J v T p o i n t

    Explanation: We will take a string “Javatpoint” and print each letter of the string except “a”. This time we will use Python while loop to do so. Until the value of the iterator is less than the string’s length, the while loop will keep executing.

    Python Continue statement in list comprehension

    Let’s see the example for continue statement in list comprehension.

    Code

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
    
      
    
    # Using a list comprehension with continue  
    
    sq_num = [num ** 2 for num in numbers if num % 2 == 0]  
    
    # This will skip odd numbers and only square the even numbers  
    
    print(sq_num)

    Output:[4, 16, 36, 64, 100]

    Explanation: In the above code, list comprehension will square the numbers from the list. And continue statement will be encountered when odd numbers come and the loop will skip the execution and moves to the next iterartion.

    Python Continue vs. Pass

    Usually, there is some confusion in the pass and continue keywords. So here are the differences between these two.

    Headingscontinuepass
    DefinitionThe continue statement is utilized to skip the current loop’s remaining statements, go to the following iteration, and return control to the beginning.The pass keyword is used when a phrase is necessary syntactically to be placed but not to be executed.
    ActionIt takes the control back to the start of the loop.Nothing happens if the Python interpreter encounters the pass statement.
    ApplicationIt works with both the Python while and Python for loops.It performs nothing; hence it is a null operation.
    SyntaxIt has the following syntax: -: continueIts syntax is as follows:- pass
    InterpretationIt’s mostly utilized within a loop’s condition.During the byte-compile stage, the pass keyword is removed.
  • 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