Author: Saim Khalid

  • User Input

    Provide User Input in Python

    In this chapter, we will learn how Python accepts the user input from the console, and displays the output on the same console.

    Every computer application should have a provision to accept input from the user when it is running. This makes the application interactive. Depending on how it is developed, an application may accept the user input in the form of text entered in the console (sys.stdin), a graphical layout, or a web-based interface.

    Python User Input Functions

    Python provides us with two built-in functions to read the input from the keyboard.

    • The input () Function
    • The raw_input () Function

    Python interpreter works in interactive and scripted mode. While the interactive mode is good for quick evaluations, it is less productive. For repeated execution of same set of instructions, scripted mode should be used.

    Let us write a simple Python script to start with.

    #! /usr/bin/python3.11
    
    name ="Kiran"
    city ="Hyderabad"print("Hello My name is", name)print("I am from", city)

    Save the above code as hello.py and run it from the command-line. Here’s the output

    C:\python311> python hello.py
    Hello My name is Kiran
    I am from Hyderabad
    

    The program simply prints the values of the two variables in it. If you run the program repeatedly, the same output will be displayed every time. To use the program for another name and city, you can edit the code, change name to say “Ravi” and city to “Chennai”. Every time you need to assign different value, you will have to edit the program, save and run, which is not the ideal way.

    The input() Function

    Obviously, you need some mechanism to assign different value to the variable in the runtime − while the program is running. Python’s input() function does the same job.

    Following is the syntax of Python’s standard library input() function.

    >>> var =input()

    When the interpreter encounters input() function, it waits for the user to enter data from the standard input stream (keyboard) till the Enter key is pressed. The sequence of characters may be stored in a string variable for further use.

    On reading the Enter key, the program proceeds to the next statement. Let use change our program to store the user input in name and city variables.

    #! /usr/bin/python3.11
    
    name =input()
    city =input()print("Hello My name is", name)print("I am from ", city)

    When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed.

    Ravi
    Chennai
    Hello My name is Ravi
    I am from Chennai
    

    Now, the variables are not assigned any specific value in the program. Every time you run, different values can be input. So, your program has become truly interactive.

    Inside the input() function, you may give a prompt text, which will appear before the cursor when you run the code.

    #! /usr/bin/python3.11
    
    name =input("Enter your name : ")
    city =input("Enter your city : ")print("Hello My name is", name)print("I am from ", city)

    When you run the program displays the prompt message, basically helping the user what to enter.

    Enter your name: Praveen Rao
    Enter your city: Bengaluru
    Hello My name is Praveen Rao
    I am from Bengaluru
    

    The raw_input() Function

    The raw_input() function works similar to input() function. Here only point is that this function was available in Python 2.7, and it has been renamed to input() in Python 3.6

    Following is the syntax of the raw_input() function:

    >>> var =raw_input([prompt text])

    Let’s re-write the above program using raw_input() function:

    #! /usr/bin/python3.11
    
    name =raw_input("Eneter your name - ")
    city =raw_input("Enter city name - ")print("Hello My name is", name)print("I am from ", city)

    When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed.

    Eneter your name - Ravi
    Enter city name - Chennai
    Hello My name is Ravi
    I am from Chennai
    

    Taking Numeric Input in Python

    Let us write a Python code that accepts width and height of a rectangle from the user and computes the area.

    #! /usr/bin/python3.11
    
    width =input("Enter width : ")
    height =input("Enter height : ")
    
    area = width*height
    print("Area of rectangle = ", area)

    Run the program, and enter width and height.

    Enter width: 20
    Enter height: 30
    Traceback (most recent call last):
      File "C:\Python311\var1.py", line 5, in <module>
       area = width*height
    TypeError: can't multiply sequence by non-int of type 'str'
    

    Why do you get a TypeError here? The reason is, Python always read the user input as a string. Hence, width=”20″ and height=”30″ are the strings and obviously you cannot perform multiplication of two strings.

    To overcome this problem, we shall use int(), another built-in function from Python’s standard library. It converts a string object to an integer.

    To accept an integer input from the user, read the input in a string, and type cast it to integer with int() function −

    w =input("Enter width : ")
    width =int(w)
    
    h =input("Enter height : ")
    height =int(h)

    You can combine the input and type cast statements in one −

    #! /usr/bin/python3.11
    
    width =int(input("Enter width : "))
    height =int(input("Enter height : "))
    
    area = width*height
    print("Area of rectangle = ", area)

    Now you can input any integer value to the two variables in the program −

    Enter width: 20
    Enter height: 30
    Area of rectangle = 600
    Python's float() function converts a string into a float object. The following program accepts the user input and parses it to a float variable − rate, and computes the interest on an amount which is also input by the user.

    #! /usr/bin/python3.11

    amount = float(input("Enter Amount : "))
    rate = float(input("Enter rate of interest : "))

    interest = amount*rate/100
    print ("Amount: ", amount, "Interest: ", interest)
    The program ask user to enter amount and rate; and displays the result as follows −

    Enter Amount: 12500
    Enter rate of interest: 6.5
    Amount: 12500.0 Interest: 812.5
    The print() Function
    Python's print() function is a built-in function. It is the most frequently used function, that displays value of Python expression given in parenthesis, on Python's console, or standard output (sys.stdout).

    print ("Hello World ")
    Any number of Python expressions can be there inside the parenthesis. They must be separated by comma symbol. Each item in the list may be any Python object, or a valid Python expression.

    #! /usr/bin/python3.11

    a = "Hello World"
    b = 100
    c = 25.50
    d = 5+6j
    print ("Message: a)
    print (b, c, b-c)
    print(pow(100, 0.5), pow(c,2))
    The first call to print() displays a string literal and a string variable. The second prints value of two variables and their subtraction. The pow() function computes the square root of a number and square value of a variable.

    Message Hello World
    100 25.5 74.5
    10.0 650.25
    If there are multiple comma separated objects in the print() function's parenthesis, the values are separated by a white space " ". To use any other character as a separator, define a sep parameter for the print() function. This parameter should follow the list of expressions to be printed.

    In the following output of print() function, the variables are separated by comma.

    #! /usr/bin/python3.11

    city="Hyderabad"
    state="Telangana"
    country="India"
    print(city, state, country, sep=',')
    The effect of sep=',' can be seen in the result −

    Hyderabad,Telangana,India
    The print() function issues a newline character ('\n') at the end, by default. As a result, the output of the next print() statement appears in the next line of the console.

    city="Hyderabad"
    state="Telangana"
    print("City:", city)
    print("State:", state)
    Two lines are displayed as the output −

    City: Hyderabad
    State: Telangana
    To make these two lines appear in the same line, define end parameter in the first print() function and set it to a whitespace string " ".

    Open Compiler
    city="Hyderabad"
    state="Telangana"
    country="India"

    print("City:", city, end=" ")
    print("State:", state)
    Output of both the print() functions appear in continuation.

    City: Hyderabad State: Telangana
  •  Comments

    Python Comments

    Python comments are programmer-readable explanation or annotations in the Python source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Python interpreter. Comments enhance the readability of the code and help the programmers to understand the code very carefully.

    Example

    If we execute the code given below, the output produced will simply print “Hello, World!” to the console, as comments are ignored by the Python interpreter and do not affect the execution of the program −

    # This is a commentprint("Hello, World!")

    Python supports three types of comments as shown below −

    • Single-line comments
    • Multi-line comments
    • Docstring Comments

    Advertisement

    Single Line Comments in Python

    Single-line comments in Python start with a hash symbol (#) and extend to the end of the line. They are used to provide short explanations or notes about the code. They can be placed on their own line above the code they describe, or at the end of a line of code (known as an inline comment) to provide context or clarification about that specific line.

    Example: Standalone Single-Line Comment

    A standalone single-line comment is a comment that occupies an entire line by itself, starting with a hash symbol (#). It is placed above the code it describes or annotates.

    In this example, the standalone single-line comment is placed above the “greet” function “−

    # Standalone single line comment is placed heredefgreet():print("Hello, World!")
    greet()

    Example: Inline Single-Line Comment

    An inline single-line comment is a comment that appears on the same line as a piece of code, following the code and preceded by a hash symbol (#).

    In here, the inline single-line comment follows the print(“Hello, World!”) statement −

    print("Hello, World!")# Inline single line comment is placed here

    Multi Line Comments in Python

    In Python, multi-line comments are used to provide longer explanations or notes that span multiple lines. While Python does not have a specific syntax for multi-line comments, there are two common ways to achieve this: consecutive single-line comments and triple-quoted strings −

    Consecutive Single-Line Comments

    Consecutive single-line comments refers to using the hash symbol (#) at the beginning of each line. This method is often used for longer explanations or to section off parts of the code.

    Example

    In this example, multiple lines of comments are used to explain the purpose and logic of the factorial function −

    # This function calculates the factorial of a number# using an iterative approach. The factorial of a number# n is the product of all positive integers less than or# equal to n. For example, factorial(5) is 5*4*3*2*1 = 120.deffactorial(n):if n <0:return"Factorial is not defined for negative numbers"
       result =1for i inrange(1, n +1):
    
      result *= i
    return result number =5print(f"The factorial of {number} is {factorial(number)}")

    Multi Line Comment Using Triple Quoted Strings

    We can use triple-quoted strings (”’ or “””) to create multi-line comments. These strings are technically string literals but can be used as comments if they are not assigned to any variable or used in expressions.

    This pattern is often used for block comments or when documenting sections of code that require detailed explanations.

    Example

    Here, the triple-quoted string provides a detailed explanation of the “gcd” function, describing its purpose and the algorithm used −

    """
    This function calculates the greatest common divisor (GCD)
    of two numbers using the Euclidean algorithm. The GCD of
    two numbers is the largest number that divides both of them
    without leaving a remainder.
    """defgcd(a, b):while b:
    
      a, b = b, a % b
    return a result = gcd(48,18)print("The GCD of 48 and 18 is:", result)

    Using Comments for Documentation

    In Python, documentation comments, also known as docstrings, provide a way to incorporate documentation within your code. This can be useful for explaining the purpose and usage of modules, classes, functions, and methods. Effective use of documentation comments helps other developers understand your code and its purpose without needing to read through all the details of the implementation.

    Python Docstrings

    In Python, docstrings are a special type of comment that is used to document modules, classes, functions, and methods. They are written using triple quotes (”’ or “””) and are placed immediately after the definition of the entity they document.

    Docstrings can be accessed programmatically, making them an integral part of Pythons built-in documentation tools.

    Example of a Function Docstring

    defgreet(name):"""
       This function greets the person whose name is passed as a parameter.
    
       Parameters:
       name (str): The name of the person to greet
    
       Returns:
       None
       """print(f"Hello, {name}!")
    greet("Alice")

    Accessing Docstrings

    Docstrings can be accessed using the .__doc__ attribute or the help() function. This makes it easy to view the documentation for any module, class, function, or method directly from the interactive Python shell or within the code.

    Example: Using the .__doc__ attribute

    defgreet(name):"""
    
    This function greets the person whose name is passed as a parameter.
    Parameters:
    name (str): The name of the person to greet
    Returns:
    None
    """print(greet.__doc__)</pre>

    Example: Using the help() Function

    Open Compiler

    defgreet(name):"""
    
    This function greets the person whose name is passed as a parameter.
    Parameters:
    name (str): The name of the person to greet
    Returns:
    None
    """help(greet)</pre>
  • Operator Precedence

    Python Operator Precedence

    An expression may have multiple operators to be evaluated. The operator precedence defines the order in which operators are evaluated. In other words, the order of operator evaluation is determined by the operator precedence.

    If a certain expression contains multiple operators, their order of evaluation is determined by the order of precedence. For example, consider the following expression

    >>> a =2+3*5

    Here, what will be the value of a? – yes it will be 17 (multiply 3 by 5 first and then add 2) or 25 (adding 2 and 3 and then multiply with 5)? Pythons operator precedence rule comes into picture here.

    If we consider only the arithmetic operators in Python, the traditional BODMAS rule is also employed by Python interpreter, where the brackets are evaluated first, the division and multiplication operators next, followed by addition and subtraction operators. Hence, a will become 17 in the above expression.

    In addition to the operator precedence, the associativity of operators is also important. If an expression consists of operators with same level of precedence, the associativity determines the order. Most of the operators have left to right associativity. It means, the operator on the left is evaluated before the one on the right.

    Let us consider another expression:

    >>> b =10/5*4

    In this case, both * (multiplication) and / (division) operators have same level of precedence. However, the left to right associativity rule performs the division first (10/5 = 2) and then the multiplication (2*4 = 8).

    Python Operator Precedence Table

    The following table lists all the operators in Python in their decreasing order of precedence. Operators in the same cell under the Operators column have the same precedence.

    Sr.No.Operator & Description
    1(),[], {}Parentheses and braces
    2[index], [index:index]Subscription, slicing,
    3await xAwait expression
    4**Exponentiation
    5+x, -x, ~xPositive, negative, bitwise NOT
    6*, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder
    7+, –Addition and subtraction
    8<<, >>Left Shifts, Right Shifts
    9&Bitwise AND
    10^Bitwise XOR
    11|Bitwise OR
    12in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests
    13not xBoolean NOT
    14andBoolean AND
    15orBoolean OR
    16if elseConditional expression
    17lambdaLambda expression
    18:=Walrus operator

    Python Operator Precedence Example

    a =20
    b =10
    c =15
    d =5
    e =0
    
    e =(a + b)* c / d       #( 30 * 15 ) / 5print("Value of (a + b) * c / d is ",  e)
    
    e =((a + b)* c)/ d     # (30 * 15 ) / 5print("Value of ((a + b) * c) / d is ",  e)
    
    e =(a + b)*(c / d);# (30) * (15/5)print("Value of (a + b) * (c / d) is ",  e)
    
    e = a +(b * c)/ d;#  20 + (150/5)print("Value of a + (b * c) / d is ",  e)

    When you execute the above program, it produces the following result −

    Value of (a + b) * c / d is  90.0
    Value of ((a + b) * c) / d is  90.0
    Value of (a + b) * (c / d) is  90.0
    Value of a + (b * c) / d is  50.0
  • Identity Operators


    Python Identity Operators

    The identity operators compare the objects to determine whether they share the same memory and refer to the same object type (data type).

    Python provided two identity operators; we have listed them as follows:

    • is‘ Operator
    • is not‘ Operator

    Python ‘is’ Operator

    The ‘is‘ operator evaluates to True if both the operand objects share the same memory location. The memory location of the object can be obtained by the “id()” function. If the “id()” of both variables is same, the “is” operator returns True.

    Example of Python Identity ‘is’ Operator

    a =[1,2,3,4,5]
    b =[1,2,3,4,5]
    c = a
    
    # Comparing and printing return valuesprint(a is c)print(a is b)# Printing IDs of a, b, and cprint("id(a) : ",id(a))print("id(b) : ",id(b))print("id(c) : ",id(c))

    It will produce the following output −

    True
    False
    id(a) :  140114091859456
    id(b) :  140114091906944
    id(c) :  140114091859456
    

    Python ‘is not’ Operator

    The ‘is not‘ operator evaluates to True if both the operand objects do not share the same memory location or both operands are not the same objects.

    Example of Python Identity ‘is not’ Operator

    a =[1,2,3,4,5]
    b =[1,2,3,4,5]
    c = a
    
    # Comparing and printing return valuesprint(a isnot c)print(a isnot b)# Printing IDs of a, b, and cprint("id(a) : ",id(a))print("id(b) : ",id(b))print("id(c) : ",id(c))

    It will produce the following output −

    False
    True
    id(a) :  140559927442176
    id(b) :  140559925598080
    id(c) :  140559927442176
    

    Python Identity Operators Examples with Explanations

    Example 1

    a="TutorialsPoint"
    b=a
    print("id(a), id(b):",id(a),id(b))print("a is b:", a is b)print("b is not a:", b isnot a)

    It will produce the following output −

    id(a), id(b): 2739311598832 2739311598832
    a is b: True
    b is not a: False
    

    The list and tuple objects behave differently, which might look strange in the first instance. In the following example, two lists “a” and “b” contain same items. But their id() differs.

    Example 2

    a=[1,2,3]
    b=[1,2,3]print("id(a), id(b):",id(a),id(b))print("a is b:", a is b)print("b is not a:", b isnot a)

    It will produce the following output −

    id(a), id(b): 1552612704640 1552567805568
    a is b: False
    b is not a: True
    

    The list or tuple contains the memory locations of individual items only and not the items itself. Hence “a” contains the addresses of 10,20 and 30 integer objects in a certain location which may be different from that of “b”.

    Example 3

    print(id(a[0]),id(a[1]),id(a[2]))print(id(b[0]),id(b[1]),id(b[2]))

    It will produce the following output −

    140734682034984 140734682035016 140734682035048
    140734682034984 140734682035016 140734682035048
    

    Because of two different locations of “a” and “b”, the “is” operator returns False even if the two lists contain same numbers.

  • Membership Operators

    Python Membership Operators

    The membership operators in Python help us determine whether an item is present in a given container type object, or in other words, whether an item is a member of the given container type object.

    Types of Python Membership Operators

    Python has two membership operators: in and not in. Both return a Boolean result. The result of in operator is opposite to that of not in operator.

    The ‘in’ Operator

    The “in” operator is used to check whether a substring is present in a bigger string, any item is present in a list or tuple, or a sub-list or sub-tuple is included in a list or tuple.

    Example of Python Membership “in” Operator

    In the following example, different substrings are checked whether they belong to the string var=”TutorialsPoint”. Python differentiates characters on the basis of their Unicode value. Hence “To” is not the same as “to”. Also note that if the “in” operator returns True, the “not in” operator evaluates to False

    var ="TutorialsPoint"
    a ="P"
    b ="tor"
    c ="in"
    d ="To"print(a,"in", var,":", a in var)print(b,"in", var,":", b in var)print(c,"in", var,":", c in var)print(d,"in", var,":", d in var)

    It will produce the following output −

    P in TutorialsPoint : True
    tor in TutorialsPoint : True
    in in TutorialsPoint : True
    To in TutorialsPoint : False
    

    The ‘not in’ Operator

    The “not in” operator is used to check a sequence with the given value is not present in the object like string, listtuple, etc.

    Example of Python Membership “not in” Operator

    var ="TutorialsPoint"
    a ="P"
    b ="tor"
    c ="in"
    d ="To"print(a,"not in", var,":", a notin var)print(b,"not in", var,":", b notin var)print(c,"not in", var,":", c notin var)print(d,"not in", var,":", d notin var)

    It will produce the following output −

    P not in TutorialsPoint : False
    tor not in TutorialsPoint : False
    in not in TutorialsPoint : False
    To not in TutorialsPoint : True
    

    Membership Operator with Lists and Tuples

    You can use the “in/not in” operator to check the membership of an item in the list or tuple.

    var =[10,20,30,40]
    a =20
    b =10
    c = a-b
    d = a/2print(a,"in", var,":", a in var)print(b,"not in", var,":", b notin var)print(c,"in", var,":", c in var)print(d,"not in", var,":", d notin var)

    It will produce the following output −

    20 in [10, 20, 30, 40] : True
    10 not in [10, 20, 30, 40] : False
    10 in [10, 20, 30, 40] : True
    10.0 not in [10, 20, 30, 40] : False
    

    In the last case, “d” is a float but still it compares to True with 10 (an int) in the list. Even if a number expressed in other formats like binary, octal or hexadecimal are given the membership operators tell if it is inside the sequence.

    >>>0x14in[10,20,30,40]True

    Example

    However, if you try to check if two successive numbers are present in a list or tuple, the in operator returns False. If the list/tuple contains the successive numbers as a sequence itself, then it returns True.

    var =(10,20,30,40)
    a =10
    b =20print((a,b),"in", var,":",(a,b)in var)
    var =((10,20),30,40)
    a =10
    b =20print((a,b),"in", var,":",(a,b)in var)

    It will produce the following output −

    (10, 20) in (10, 20, 30, 40) : False
    (10, 20) in ((10, 20), 30, 40) : True
    

    Membership Operator with Sets

    Python’s membership operators also work well with the set objects.

    var ={10,20,30,40}
    a =10
    b =20print(b,"in", var,":", b in var)
    var ={(10,20),30,40}
    a =10
    b =20print((a,b),"in", var,":",(a,b)in var)

    It will produce the following output −

    20 in {40, 10, 20, 30} : True
    (10, 20) in {40, 30, (10, 20)} : True
    

    Membership Operator with Dictionaries

    Use of in as well as not in operators with dictionary object is allowed. However, Python checks the membership only with the collection of keys and not values.

    var ={1:10,2:20,3:30}
    a =2
    b =20print(a,"in", var,":", a in var)print(b,"in", var,":", b in var)

    It will produce the following output −

    2 in {1: 10, 2: 20, 3: 30} : True
    20 in {1: 10, 2: 20, 3: 30} : False
    

  • Bitwise Operators

    Python Bitwise Operators

    Python bitwise operators are normally used to perform bitwise operations on integer-type objects. However, instead of treating the object as a whole, it is treated as a string of bits. Different operations are done on each bit in the string.

    Python has six bitwise operators – &, |, ^, ~, << and >>. All these operators (except ~) are binary in nature, in the sense they operate on two operands. Each operand is a binary digit (bit) 1 or 0.

    The following are the bitwise operators in Python –

    • Bitwise AND Operator
    • Bitwise OR Operator
    • Bitwise XOR Operator
    • Bitwise NOT Operator
    • Bitwise Left Shift Operator
    • Biwtise Right Shift Operator

    Python Bitwise AND Operator (&)

    Bitwise AND operator is somewhat similar to logical and operator. It returns True only if both the bit operands are 1 (i.e. True). All the combinations are −

    0 & 0 is 0
    1 & 0 is 0
    0 & 1 is 0
    1 & 1 is 1
    

    When you use integers as the operands, both are converted in equivalent binary, the & operation is done on corresponding bit from each number, starting from the least significant bit and going towards most significant bit.

    Example of Bitwise AND Operator in Python

    Let us take two integers 60 and 13, and assign them to variables a and b respectively.

    a=60
    b=13print("a:",a,"b:",b,"a&b:",a&b)

    It will produce the following output −

    a: 60 b: 13 a&b: 12
    

    To understand how Python performs the operation, obtain the binary equivalent of each variable.

    print("a:",bin(a))print("b:",bin(b))

    It will produce the following output −

    a: 0b111100
    b: 0b1101
    

    For the sake of convenience, use the standard 8-bit format for each number, so that “a” is 00111100 and “b” is 00001101. Let us manually perform and operation on each corresponding bits of these two numbers.

    0011 1100
    &
    0000 1101
    -------------
    0000 1100
    

    Convert the resultant binary back to integer. You’ll get 12, which was the result obtained earlier.

    >>>int('00001100',2)12

    Python Bitwise OR Operator (|)

    The “|” symbol (called pipe) is the bitwise OR operator. If any bit operand is 1, the result is 1 otherwise it is 0.

    0 | 0 is 0
    0 | 1 is 1
    1 | 0 is 1
    1 | 1 is 1
    

    Example of Bitwise OR Operator in Python

    Take the same values of a=60, b=13. The “|” operation results in 61. Obtain their binary equivalents.

    a=60
    b=13print("a:",a,"b:",b,"a|b:",a|b)print("a:",bin(a))print("b:",bin(b))

    It will produce the following output −

    a: 60 b: 13 a|b: 61
    a: 0b111100
    b: 0b1101
    

    To perform the “|” operation manually, use the 8-bit format.

    0011 1100
    
    |
    0000 1101 ------------- 0011 1101

    Convert the binary number back to integer to tally the result −

    >>>int('00111101',2)61

    Python Bitwise XOR Operator (^)

    The term XOR stands for exclusive OR. It means that the result of OR operation on two bits will be 1 if only one of the bits is 1.

    0^0is00^1is11^0is11^1is0

    Example of Bitwise XOR Operator in Python

    Let us perform XOR operation on a=60 and b=13.

    a=60
    b=13print("a:",a,"b:",b,"a^b:",a^b)

    It will produce the following output −

    a: 60 b: 13 a^b: 49
    

    We now perform the bitwise XOR manually.

    0011 1100
    
    ^
    0000 1101 ------------- 0011 0001

    The int() function shows 00110001 to be 49.

    >>>int('00110001',2)49

    Python Bitwise NOT Operator (~)

    This operator is the binary equivalent of logical NOT operator. It flips each bit so that 1 is replaced by 0, and 0 by 1, and returns the complement of the original number. Python uses 2’s complement method. For positive integers, it is obtained simply by reversing the bits. For negative number, -x, it is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). Hence: (for 8 bit representation)

    -1is complement(1-1)= complement(0)="11111111"-10is complement(10-1)= complement(9)= complement("00001001")="11110110".

    Example of Bitwise NOT Operator in Python

    For a=60, its complement is −

    a=60print("a:",a,"~a:",~a)

    It will produce the following output −

    a: 60 ~a: -61
    

    Python Bitwise Left Shift Operator (<<)

    Left shift operator shifts most significant bits to right by the number on the right side of the “<<” symbol. Hence, “x << 2” causes two bits of the binary representation of to right.

    Example of Bitwise Left Shift Operator in Python

    Let us perform left shift on 60.

    a=60print("a:",a,"a<<2:", a<<2)

    It will produce the following output −

    a: 60 a<<2: 240
    

    How does this take place? Let us use the binary equivalent of 60, and perform the left shift by 2.

    00111100<<2-------------11110000

    Convert the binary to integer. It is 240.

    >>>int('11110000',2)240

    Python Bitwise Right Shift Operator (>>)

    Right shift operator shifts least significant bits to left by the number on the right side of the “>>” symbol. Hence, “x >> 2” causes two bits of the binary representation of to left.

    Example of Bitwise Right Shift Operator in Python

    Let us perform right shift on 60.

    a=60print("a:",a,"a>>2:", a>>2)

    It will produce the following output −

    a: 60 a>>2: 15
    

    Manual right shift operation on 60 is shown below −

    00111100>>2-------------00001111

    Use int() function to covert the above binary number to integer. It is 15.

    >>>int('00001111',2)15
  • Logical Operators

    Python Logical Operators

    Python logical operators are used to form compound Boolean expressions. Each operand for these logical operators is itself a Boolean expression. For example,

    Example

    age >16and marks >80
    percentage <50or attendance <75

    Along with the keyword False, Python interprets None, numeric zero of all types, and empty sequences (stringstupleslists), empty dictionaries, and empty sets as False. All other values are treated as True.

    There are three logical operators in Python. They are “and“, “or” and “not“. They must be in lowercase.

    Logical “and” Operator

    For the compound Boolean expression to be True, both the operands must be True. If any or both operands evaluate to False, the expression returns False.

    Logical “and” Operator Truth Table

    The following table shows the scenarios.

    aba and b
    FFF
    FTF
    TFF
    TTT

    Logical “or” Operator

    In contrast, the or operator returns True if any of the operands is True. For the compound Boolean expression to be False, both the operands have to be False.

    Logical “or” Operator Truth Table

    The following tables shows the result of the “or” operator with different conditions:

    aba or b
    FFF
    FTT
    TFT
    TTT

    Logical “not” Operator

    This is a unary operator. The state of Boolean operand that follows, is reversed. As a result, not True becomes False and not False becomes True.

    Logical “not” Operator Truth Table

    anot (a)
    FT
    TF

    How the Python interpreter evaluates the logical operators?

    The expression “x and y” first evaluates “x”. If “x” is false, its value is returned; otherwise, “y” is evaluated and the resulting value is returned.

    logical_operator

    The expression “x or y” first evaluates “x”; if “x” is true, its value is returned; otherwise, “y” is evaluated and the resulting value is returned.

    x_or_y

    Python Logical Operators Examples

    Some use cases of logical operators are given below −

    Example 1: Logical Operators With Boolean Conditions

    x =10
    y =20print("x > 0 and x < 10:",x >0and x <10)print("x > 0 and y > 10:",x >0and y >10)print("x > 10 or y > 10:",x >10or y >10)print("x%2 == 0 and y%2 == 0:",x%2==0and y%2==0)print("not (x+y>15):",not(x+y)>15)

    It will produce the following output −

    x > 0 and x < 10: False
    x > 0 and y > 10: True
    x > 10 or y > 10: True
    x%2 == 0 and y%2 == 0: True
    not (x+y>15): False
    

    Example 2: Logical Operators With Non- Boolean Conditions

    We can use non-boolean operands with logical operators. Here, we need to not that any non-zero numbers, and non-empty sequences evaluate to True. Hence, the same truth tables of logical operators apply.

    In the following example, numeric operands are used for logical operators. The variables “x”, “y” evaluate to True, “z” is False

    x =10
    y =20
    z =0print("x and y:",x and y)print("x or y:",x or y)print("z or x:",z or x)print("y or z:", y or z)

    It will produce the following output −

    x and y: 20
    x or y: 10
    z or x: 10
    y or z: 20
    

    Example 3: Logical Operators With Strings and Tuples

    The string variable is treated as True and an empty tuple as False in the following example −

    a="Hello"
    b=tuple()print("a and b:",a and b)print("b or a:",b or a)

    It will produce the following output −

    a and b: ()
    b or a: Hello
    

    Example 4: Logical Operators To Compare Sequences (Lists)

    Finally, two list objects below are non-empty. Hence x and y returns the latter, and x or y returns the former.

    x=[1,2,3]
    y=[10,20,30]print("x and y:",x and y)print("x or y:",x or y)

    It will produce the following output −

    x and y: [10, 20, 30]
    x or y: [1, 2, 3]
  • Assignment Operators

    Python Assignment Operator

    The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

    Example of Assignment Operator in Python

    Consider following Python statements −

    a =10
    b =5
    a = a + b
    print(a)

    At the first instance, at least for somebody new to programming but who knows maths, the statement “a=a+b” looks strange. How could a be equal to “a+b”? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.

    Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.

    In the statement “a+=b”, the two operators “+” and “=” can be combined in a “+=” operator. It is called as add and assign operator. In a single statement, it performs addition of two operands “a” and “b”, and result is assigned to operand on left, i.e., “a”.

    Augmented Assignment Operators in Python

    In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.

    Python has the augmented assignment operators for all arithmetic and comparison operators.

    Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.

    Example

    The += operator is an augmented operator. It is also called cumulative addition operator, as it adds “b” in “a” and assigns the result back to a variable.

    The following are the augmented assignment operators in Python:

    • Augmented Addition Operator
    • Augmented Subtraction Operator
    • Augmented Multiplication Operator
    • Augmented Division Operator
    • Augmented Modulus Operator
    • Augmented Exponent Operator
    • Augmented Floor division Operator

    Augmented Addition Operator (+=)

    Following examples will help in understanding how the “+=” operator works −

    a=10
    b=5print("Augmented addition of int and int")
    a+=b # equivalent to a=a+bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented addition of int and float")
    a+=b  # equivalent to a=a+bprint("a=",a,"type(a):",type(a))
    
    a=10.50
    b=5+6jprint("Augmented addition of float and complex")
    a+=b #equivalent to a=a+bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented addition of int and int
    a= 15 type(a): <class 'int'>
    Augmented addition of int and float
    a= 15.5 type(a): <class 'float'>
    Augmented addition of float and complex
    a= (15.5+6j) type(a): <class 'complex'>
    

    Augmented Subtraction Operator (-=)

    Use -= symbol to perform subtract and assign operations in a single statement. The “a-=b” statement performs “a=a-b” assignment. Operands may be of any number type. Python performs implicit type casting on the object which is narrower in size.

    a=10
    b=5print("Augmented subtraction of int and int")
    a-=b #equivalent to a=a-bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented subtraction of int and float")
    a-=b #equivalent to a=a-bprint("a=",a,"type(a):",type(a))
    
    a=10.50
    b=5+6jprint("Augmented subtraction of float and complex")
    a-=b #equivalent to a=a-bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented subtraction of int and int
    a= 5 type(a): <class 'int'>
    Augmented subtraction of int and float
    a= 4.5 type(a): <class 'float'>
    Augmented subtraction of float and complex
    a= (5.5-6j) type(a): <class 'complex'>
    

    Augmented Multiplication Operator (*=)

    The “*=” operator works on similar principle. “a*=b” performs multiply and assign operations, and is equivalent to “a=a*b”. In case of augmented multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.

    applicable.

    a=10
    b=5print("Augmented multiplication of int and int")
    a*=b #equivalent to a=a*bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented multiplication of int and float")
    a*=b #equivalent to a=a*bprint("a=",a,"type(a):",type(a))
    
    a=6+4j
    b=3+2jprint("Augmented multiplication of complex and complex")
    a*=b #equivalent to a=a*bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented multiplication of int and int
    a= 50 type(a): <class 'int'>
    Augmented multiplication of int and float
    a= 55.0 type(a): <class 'float'>
    Augmented multiplication of complex and complex
    a= (10+24j) type(a): <class 'complex'>
    

    Augmented Division Operator (/=)

    The combination symbol “/=” acts as divide and assignment operator, hence “a/=b” is equivalent to “a=a/b”. The division operation of int or float operands is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.

    a=10
    b=5print("Augmented division of int and int")
    a/=b #equivalent to a=a/bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented division of int and float")
    a/=b #equivalent to a=a/bprint("a=",a,"type(a):",type(a))
    
    a=6+4j
    b=3+2jprint("Augmented division of complex and complex")
    a/=b #equivalent to a=a/bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented division of int and int
    a= 2.0 type(a): <class 'float'>
    Augmented division of int and float
    a= 1.8181818181818181 type(a): <class 'float'>
    Augmented division of complex and complex
    a= (2+0j) type(a): <class 'complex'>
    

    Augmented Modulus Operator (%=)

    To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not supported for complex number.

    a=10
    b=5print("Augmented modulus operator with int and int")
    a%=b #equivalent to a=a%bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented modulus operator with int and float")
    a%=b #equivalent to a=a%bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented modulus operator with int and int
    a= 0 type(a): <class 'int'>
    Augmented modulus operator with int and float
    a= 4.5 type(a): <class 'float'>
    

    Augmented Exponent Operator (**=)

    The “**=” operator results in computation of “a” raised to “b”, and assigning the value back to “a”. Given below are some examples −

    a=10
    b=5print("Augmented exponent operator with int and int")
    a**=b #equivalent to a=a**bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented exponent operator with int and float")
    a**=b #equivalent to a=a**bprint("a=",a,"type(a):",type(a))
    
    a=6+4j
    b=3+2jprint("Augmented exponent operator with complex and complex")
    a**=b #equivalent to a=a**bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented exponent operator with int and int
    a= 100000 type(a): <class 'int'>
    Augmented exponent operator with int and float
    a= 316227.7660168379 type(a): <class 'float'>
    Augmented exponent operator with complex and complex
    a= (97.52306038414744-62.22529992036203j) type(a): <class 'complex'>
    

    Augmented Floor division Operator (//=)

    For performing floor division and assignment in a single statement, use the “//=” operator. “a//=b” is equivalent to “a=a//b”. This operator cannot be used with complex numbers.

    a=10
    b=5print("Augmented floor division operator with int and int")
    a//=b #equivalent to a=a//bprint("a=",a,"type(a):",type(a))
    
    a=10
    b=5.5print("Augmented floor division operator with int and float")
    a//=b #equivalent to a=a//bprint("a=",a,"type(a):",type(a))

    It will produce the following output −

    Augmented floor division operator with int and int a= 2 type(a): <class ‘int’> Augmented floor division operator with int and float a= 1.0 type(a): <class ‘float’>

  • Comparison Operators

    Python Comparison Operators

    Comparison operators in Python are very important in Python’s conditional statements (if, else and elif) and looping statements (while and for loops). The comparison operators also called relational operators. Some of the well known operators are “<” stands for less than, and “>” stands for greater than operator.

    Python uses two more operators, combining “=” symbol with these two. The “<=” symbol is for less than or equal to operator and the “>=” symbol is for greater than or equal to operator.

    Different Comparison Operators in Python

    Python has two more comparison operators in the form of “==” and “!=”. They are for is equal to and is not equal to operators. Hence, there are six comparison operators in Python and they are listed below in this table:

    <Less thana<b
    >Greater thana>b
    <=Less than or equal toa<=b
    >=Greater than or equal toa>=b
    ==Is equal toa==b
    !=Is not equal toa!=b

    Comparison operators are binary in nature, requiring two operands. An expression involving a comparison operator is called a Boolean expression, and always returns either True or False.

    Example

    a=5
    b=7print(a>b)print(a<b)

    It will produce the following output −

    False
    True
    

    Both the operands may be Python literalsvariables or expressions. Since Python supports mixed arithmetic, you can have any number type operands.

    Example

    The following code demonstrates the use of Python’s comparison operators with integer numbers −

    print("Both operands are integer")
    a=5
    b=7print("a=",a,"b=",b,"a>b is", a>b)print("a=",a,"b=",b,"a<b is",a<b)print("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    Both operands are integer
    a= 5 b= 7 a>b is False
    a= 5 b= 7 a<b is True
    a= 5 b= 7 a==b is False
    a= 5 b= 7 a!=b is True
    

    Comparison of Float Number

    In the following example, an integer and a float operand are compared.

    Example

    print("comparison of int and float")
    a=10
    b=10.0print("a=",a,"b=",b,"a>b is", a>b)print("a=",a,"b=",b,"a<b is",a<b)print("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    comparison of int and float
    a= 10 b= 10.0 a>b is False
    a= 10 b= 10.0 a<b is False
    a= 10 b= 10.0 a==b is True
    a= 10 b= 10.0 a!=b is False
    

    Comparison of Complex umbers

    Although complex object is a number data type in Python, its behavior is different from others. Python doesn’t support < and > operators, however it does support equality (==) and inequality (!=) operators.

    Example

    print("comparison of complex numbers")
    a=10+1j
    b=10.-1jprint("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    comparison of complex numbers
    a= (10+1j) b= (10-1j) a==b is False
    a= (10+1j) b= (10-1j) a!=b is True
    

    You get a TypeError with less than or greater than operators.

    Example

    print("comparison of complex numbers")
    a=10+1j
    b=10.-1jprint("a=",a,"b=",b,"a<b is",a<b)print("a=",a,"b=",b,"a>b is",a>b)

    It will produce the following output −

    comparison of complex numbers
    Traceback (most recent call last):
      File "C:\Users\mlath\examples\example.py", line 5, in <module>
    
    print ("a=",a, "b=",b,"a&lt;b is",a&lt;b)
                                      ^^^
    TypeError: '<' not supported between instances of 'complex' and 'complex

    Comparison of Booleans

    Boolean objects in Python are really integers: True is 1 and False is 0. In fact, Python treats any non-zero number as True. In Python, comparison of Boolean objects is possible. “False < True” is True!

    Example

    print("comparison of Booleans")
    a=True
    b=Falseprint("a=",a,"b=",b,"a<b is",a<b)print("a=",a,"b=",b,"a>b is",a>b)print("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    comparison of Booleans
    a= True b= False a<b is False
    a= True b= False a>b is True
    a= True b= False a==b is False
    a= True b= False a!=b is True
    

    Comparison of Sequence Types

    In Python, comparison of only similar sequence objects can be performed. A string object is comparable with another string only. A list cannot be compared with a tuple, even if both have same items.

    Example

    print("comparison of different sequence types")
    a=(1,2,3)
    b=[1,2,3]print("a=",a,"b=",b,"a<b is",a<b)

    It will produce the following output −

    comparison of different sequence types
    Traceback (most recent call last):
      File "C:\Users\mlath\examples\example.py", line 5, in <module>
    
    print ("a=",a, "b=",b,"a&lt;b is",a&lt;b)
                                       ^^^
    TypeError: '<' not supported between instances of 'tuple' and 'list'

    Sequence objects are compared by lexicographical ordering mechanism. The comparison starts from item at 0th index. If they are equal, comparison moves to next index till the items at certain index happen to be not equal, or one of the sequences is exhausted. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.

    Which of the operands is greater depends on the difference in values of items at the index where they are unequal. For example, ‘BAT’>’BAR’ is True, as T comes after R in Unicode order.

    If all items of two sequences compare equal, the sequences are considered equal.

    Example

    print("comparison of strings")
    a='BAT'
    b='BALL'print("a=",a,"b=",b,"a<b is",a<b)print("a=",a,"b=",b,"a>b is",a>b)print("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    comparison of strings
    a= BAT b= BALL a<b is False
    a= BAT b= BALL a>b is True
    a= BAT b= BALL a==b is False
    a= BAT b= BALL a!=b is True
    

    In the following example, two tuple objects are compared −

    Example

    print("comparison of tuples")
    a=(1,2,4)
    b=(1,2,3)print("a=",a,"b=",b,"a<b is",a<b)print("a=",a,"b=",b,"a>b is",a>b)print("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    a= (1, 2, 4) b= (1, 2, 3) a<b is False
    a= (1, 2, 4) b= (1, 2, 3) a>b is True
    a= (1, 2, 4) b= (1, 2, 3) a==b is False
    a= (1, 2, 4) b= (1, 2, 3) a!=b is True
    

    Comparison of Dictionary Objects

    The use of “<” and “>” operators for Python’s dictionary is not defined. In case of these operands, TypeError: ‘<‘ not supported between instances of ‘dict’ and ‘dict’ is reported.

    Equality comparison checks if the length of both the dict items is same. Length of dictionary is the number of key-value pairs in it.

    Python dictionaries are simply compared by length. The dictionary with fewer elements is considered less than a dictionary with more elements.

    Example

    print("comparison of dictionary objects")
    a={1:1,2:2}
    b={2:2,1:1,3:3}print("a=",a,"b=",b,"a==b is",a==b)print("a=",a,"b=",b,"a!=b is",a!=b)

    It will produce the following output −

    comparison of dictionary objects
    a= {1: 1, 2: 2} b= {2: 2, 1: 1, 3: 3} a==b is False
    a= {1: 1, 2: 2} b= {2: 2, 1: 1, 3: 3} a!=b is True
  • Arithmetic Operators

    Python Arithmetic Operators

    Python arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, division, and more on numbers. Arithmetic operators are binary operators in the sense they operate on two operands. Python fully supports mixed arithmetic. That is, the two operands can be of two different number types. In such a situation.

    Types of Arithmetic Operators

    Following is the table which lists down all the arithmetic operators available in Python:

    OperatorNameExample
    +Additiona + b = 30
    Subtractiona b = -10
    *Multiplicationa * b = 200
    /Divisionb / a = 2
    %Modulusb % a = 0
    **Exponenta**b =10**20
    //Floor Division9//2 = 4

    Let us study these operators with examples.

    Addition Operator

    The addition operator represents by + symbol. It is a basic arithmetic operator. It adds the two numeric operands on the either side and returns the addition result.

    Example to add two integer numbers

    In the following example, the two integer variables are the operands for the “+” operator.

    a=10
    b=20print("Addition of two integers")print("a =",a,"b =",b,"addition =",a+b)

    It will produce the following output −

    Addition of two integers
    a = 10 b = 20 addition = 30
    

    Example to add integer and float numbers

    Addition of integer and float results in a float.

    a=10
    b=20.5print("Addition of integer and float")print("a =",a,"b =",b,"addition =",a+b)

    It will produce the following output −

    Addition of integer and float
    a = 10 b = 20.5 addition = 30.5
    

    Example to add two complex numbers

    The result of adding float to complex is a complex number.

    a=10+5j
    b=20.5print("Addition of complex and float")print("a=",a,"b=",b,"addition=",a+b)

    It will produce the following output −

    Addition of complex and float
    a= (10+5j) b= 20.5 addition= (30.5+5j)
    

    Subtraction Operator

    The subtraction operator represents by – symbol. It subtracts the second operand from the first. The resultant number is negative if the second operand is larger.

    Example to subtract two integer numbers

    First example shows subtraction of two integers.

    First example shows subtraction of two integers.

    a=10
    b=20print("Subtraction of two integers:")print("a =",a,"b =",b,"a-b =",a-b)print("a =",a,"b =",b,"b-a =",b-a)

    Result −

    Subtraction of two integers
    a = 10 b = 20 a-b = -10
    a = 10 b = 20 b-a = 10
    

    Example to subtract integer and float numbers

    Subtraction of an integer and a float follows the same principle.

    a=10
    b=20.5print("subtraction of integer and float")print("a=",a,"b=",b,"a-b=",a-b)print("a=",a,"b=",b,"b-a=",b-a)

    It will produce the following output −

    subtraction of integer and float
    a= 10 b= 20.5 a-b= -10.5
    a= 10 b= 20.5 b-a= 10.5
    

    Example to subtract complex numbers

    In the subtraction involving a complex and a float, real component is involved in the operation.

    a=10+5j
    b=20.5print("subtraction of complex and float")print("a=",a,"b=",b,"a-b=",a-b)print("a=",a,"b=",b,"b-a=",b-a)

    It will produce the following output −

    subtraction of complex and float
    a= (10+5j) b= 20.5 a-b= (-10.5+5j)
    a= (10+5j) b= 20.5 b-a= (10.5-5j)
    

    Multiplication Operator

    The * (asterisk) symbol is defined as a multiplication operator in Python (as in many languages). It returns the product of the two operands on its either side. If any of the operands negative, the result is also negative. If both are negative, the result is positive. Changing the order of operands doesn’t change the result

    Example to multiply two integers

    a=10
    b=20print("Multiplication of two integers")print("a =",a,"b =",b,"a*b =",a*b)

    It will produce the following output −

    Multiplication of two integers
    a = 10 b = 20 a*b = 200
    

    Example to multiply integer and float numbers

    In multiplication, a float operand may have a standard decimal point notation, or a scientific notation.

    a=10
    b=20.5print("Multiplication of integer and float")print("a=",a,"b=",b,"a*b=",a*b)
    
    a=-5.55
    b=6.75E-3print("Multiplication of float and float")print("a =",a,"b =",b,"a*b =",a*b)

    It will produce the following output −

    Multiplication of integer and float
    a = 10 b = 20.5 a-b = -10.5
    Multiplication of float and float
    a = -5.55 b = 0.00675 a*b = -0.037462499999999996
    

    Example to multiply complex numbers

    For the multiplication operation involving one complex operand, the other operand multiplies both the real part and imaginary part.

    a=10+5j
    b=20.5print("Multiplication of complex and float")print("a =",a,"b =",b,"a*b =",a*b)

    It will produce the following output −

    Multiplication of complex and float
    a = (10+5j) b = 20.5 a*b = (205+102.5j)
    

    Division Operator

    The “/” symbol is usually called as forward slash. The result of division operator is numerator (left operand) divided by denominator (right operand). The resultant number is negative if any of the operands is negative. Since infinity cannot be stored in the memory, Python raises ZeroDivisionError if the denominator is 0.

    The result of division operator in Python is always a float, even if both operands are integers.

    Example to divide two numbers

    a=10
    b=20print("Division of two integers")print("a=",a,"b=",b,"a/b=",a/b)print("a=",a,"b=",b,"b/a=",b/a)

    It will produce the following output −

    Division of two integers
    a= 10 b= 20 a/b= 0.5
    a= 10 b= 20 b/a= 2.0
    

    Example to divide two float numbers

    In Division, a float operand may have a standard decimal point notation, or a scientific notation.

    a=10
    b=-20.5print("Division of integer and float")print("a=",a,"b=",b,"a/b=",a/b)
    a=-2.50
    b=1.25E2print("Division of float and float")print("a=",a,"b=",b,"a/b=",a/b)

    It will produce the following output −

    Division of integer and float
    a= 10 b= -20.5 a/b= -0.4878048780487805
    Division of float and float
    a= -2.5 b= 125.0 a/b= -0.02
    

    Example to divide complex numbers

    When one of the operands is a complex number, division between the other operand and both parts of complex number (real and imaginary) object takes place.

    a=7.5+7.5j
    b=2.5print("Division of complex and float")print("a =",a,"b =",b,"a/b =",a/b)print("a =",a,"b =",b,"b/a =",b/a)

    It will produce the following output −

    Division of complex and float
    a = (7.5+7.5j) b = 2.5 a/b = (3+3j)
    a = (7.5+7.5j) b = 2.5 b/a = (0.16666666666666666-0.16666666666666666j)
    

    If the numerator is 0, the result of division is always 0 except when denominator is 0, in which case, Python raises ZeroDivisionError wirh Division by Zero error message.

    a=0
    b=2.5print("a=",a,"b=",b,"a/b=",a/b)print("a=",a,"b=",b,"b/a=",b/a)

    It will produce the following output −

    a= 0 b= 2.5 a/b= 0.0
    Traceback (most recent call last):
      File "C:\Users\mlath\examples\example.py", line 20, in <module>
    
     print ("a=",a,"b=",b,"b/a=",b/a)
                                 ~^~
    ZeroDivisionError: float division by zero

    Modulus Operator

    Python defines the “%” symbol, which is known aa Percent symbol, as Modulus (or modulo) operator. It returns the remainder after the denominator divides the numerator. It can also be called Remainder operator. The result of the modulus operator is the number that remains after the integer quotient. To give an example, when 10 is divided by 3, the quotient is 3 and remainder is 1. Hence, 10%3 (normally pronounced as 10 mod 3) results in 1.

    Example for modulus operation on integers

    If both the operands are integer, the modulus value is an integer. If numerator is completely divisible, remainder is 0. If numerator is smaller than denominator, modulus is equal to the numerator. If denominator is 0, Python raises ZeroDivisionError.