Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore 4. Operators in Python

4. Operators in Python

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-04-29 11:38:43

Description: 4. Operators in Python

Search

Read the Text Version

Course On Python Basics UNIT - 4: OPERATORS IN PYTHON Structure 4.0 Learning Objectives 4.1 Introduction to Operators 4.2 Arithmetic Operators 4.3 Comparison Operators 4.4 Logical Operators 4.5 Bitwise Operator 4.6 Assignment Operator 4.7 Identity Operator 4.8 Membership Operator 4.9 Conditional Operator 4.10 Operator Overloading in Python 4.11 Any & All in Python 4.12 Summary 4.13 Glossary 4.14 References Page 1 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 4.0 Learning Objectives After studying this unit, you will be able to: • Understand Operators in Programming Language • Learn various operators in Python • Learn arithmetic, comparison, logical, bitwise, assignment, identity, membership, and conditional operators in Python • Understand operator overloading in Python • Explain Any & All methods in Python 4.1 Introduction to Operators In computer programming, an operator is a symbol that often indicates an activity or process. Mathematical and logical symbols were used to create these symbols. An operator is a program that can manipulate a value or operand. Operators are the building blocks of every program, and they're used for anything from counting to complicated algorithms such as security encryption. Python operators are used to manipulate values and variables in general. Standard symbols for logical and mathematical operations are represented by these symbols. (+, -, *, /, <, >) The operator module provides a collection of fast functions that correspond to Python's intrinsic operators. For example, the formula x*y Page 2 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics is similar to an operator.mul(x, y). Without the double underscores, most processes required would be those in use for special methods. Many of them have a variation that keeps the double underscores for backward compatibility. For clarity, the variations without the double underscores are recommended. 4.2 Arithmetic Operators Addition, subtraction, multiplication, division, floor division, exponent (or power), and modulus are examples of Python Arithmetic operators. In Python, all of these arithmetic operators are binary operators, which means they work with two operands. Assume variable a has a value of 60 and variable b has a value of 20. Operator Description Example + Addition Values are added on both sides of a + b = 80 the operator. - Subtraction Takes the right-hand operand and a – b = 40 subtracts it from the left-hand operand. * Multiplication Values on both sides of the a * b = 1200 operator are multiplied. / Division The right-hand operand is divided a / b = 30 by the left-hand operand. Page 3 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics % Modulus Returns the residual after dividing a % b = 0 the left-hand operand by the right- hand operand. ** Exponent Calculates exponential (power) a**b =60 to the values for operators. power 20 // Floor Division The outcome of the division of 9//2 = 4 and operands is the quotient, with the 9.0//2.0 = 4.0, - digits following the decimal point 11//3 = -4, - deleted. The result is floored or 11.0//3 = -4.0 rounded away from zero when one of the operands is negative (towards negative infinity) Page 4 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Page 5 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: 4.3 Comparison Operators In Python, a comparison operator, also known as a relational operator in Python, compares the data of two operands and gives True or False depending upon whether the condition is satisfied. There are six of them: less than, greater than, less than or equal to, greater than or equal to, equal to, not equal to, and not equal to. Let’s have a look at the comparison operators and their descriptions: Page 6 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Operator Description Syntax > Returns True only if the left operand is greater than x > y that of the right operand. < Returns True only if the left operand is less than that x < y of the right operand. == Returns True if both operands are equal to each x == y other. != Returns True if operands are not equal to each other x != y >= equal to or greater than if indeed the left operand is x >= y greater than or equal to the right operand, then true. <= A value that is less than or equal to If the left x <= y operand is smaller than or equal to the right operand, then true. Page 7 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Page 8 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: 4.4 Logical Operators We'll go through Python Logical AND, OR, and NOT Logical Operators in this sub-topic. Python Logical Operators take about two operands and perform operations on them in chunks rather than in wholes. Let’s have a look at the logical operators and their descriptions: Operator Description Syntax and Returns true if both the operands are true a and b or Returns true if either of the operands is true a or b not Returns true if the operand is false not a Page 9 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 10 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 4.5 Bitwise Operators Bitwise operators are being used in Python to perform bitwise operations on integers. The numbers are transformed to binary first, and afterward, operations are carried out bit by bit, thus the term bitwise operators. The result is then shown in decimal format. Let’s have a look at the bitwise operators and their descriptions: Operator Description Syntax & Bitwise AND x&y | Bitwise OR x|y ~ Bitwise NOT ~x ^ Bitwise XOR x^y >> Bitwise right shift x>> << Bitwise left shift x<< Page 11 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Page 12 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: 4.6 Assignment Operators The assignment operator in Python aids in the assignment of values or expressions towards the left-hand-side variable. The \"=\" symbol is used in declarative sentences and assignment expressions to indicate the assignment operator. The right-hand side value or operand is assigned towards the left-hand operand in the assignment operator. Let’s have a look at the assignment operators and their descriptions: Operator Description Syntax = Assign the right side of the expression's x = y + z value to the operand on the left. Page 13 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics += Add AND: Combine the right-side and left- a+=b a=a+b side operands, then assign them to the left operand. -= Subtract AND: Subtract the right operand a-=b a=a-b from the left operand, then assign the right operand to the left operand. *= Multiply AND: Multiply the right and left a*=b a=a*b operands, then assign the result to the left operand. /= Divide AND: Combine the left and right a/=b a=a/b operands, then assign them to the left operand. %= AND MODULUS: Uses the left and right a%=b a=a%b operands to calculate the modulus and assigns the result to the left operand. //= Divide(floor) AND: Combine the left and a//=b a=a//b right operands, then assign the value (floor) to the left operand. **= AND exponent: Calculate the value of the a**=b a=a**b exponent (raise power) using the operands and assign it to the left operand. Page 14 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics &= Bitwise ANDs the operands and assigns a a&=b a=a&b value to the left operand. |= Bitwise ORs the operands and assigns a a|=b a=a|b value to the left operand. ^= Bitwise XOR is performed on the a^=b a=a^b operands, and the left operand is assigned a value. >>= Operands are bitwise right-shifted and a a>>=b a=a>>b value is assigned to the left operand. <<= On operands, does a bitwise left shift and a <<= b a= a << assigns a value to the left operand. b Page 15 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Page 16 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: 4.7 Identity operators Identity operators in Python are being used to determine if a value belongs to a specific class or type. They're frequently utilized to figure out what kind of data a variable contains. There are a variety of identification operators to choose from, like as: • ‘is’ operator: The 'is' operator returns true if both variables on both sides of the operator refer to the same object, and false otherwise. • ‘is not’ operator: If variables on either side of the operator refer to the same object, the 'is not' operator evaluates to false, otherwise to true. Page 17 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 18 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 4.8 Membership operators Operators that validate a value's membership are known as membership operators. It checks for sequence membership, like strings, lists, or tuples. • in operator: The 'in' operator is used to determine whether a value is present in a sequence. If a variable is found in the supplied sequence, evaluate to true; otherwise, evaluate to false. • ‘not in’ operator: If it doesn't discover a variable in the supplied sequence, it returns true; otherwise, it returns false. Example: Page 19 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: 4.9 Conditional Operator Conditional operators, commonly known as ternary expressions, assess something dependent on whether or not a condition is true. Python 2.5 was the first version to include it. It simply replaces the multiline if-else with a single line to test a condition, making the code more concise. Points to remember: • The supplied condition is first assessed (a b), and then either a or b is given based on the condition's Boolean value. • In comparison to other languages such as C/C++, the order of the parameters in the operator is different. • Among all Python operations, conditional expressions get the lowest priority. Page 20 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output Page 21 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 4.10 Operator Overloading in Python Overloading an operator refers to providing them more meaning than their established operational meaning. The operator +, for example, may be used to add two numbers, connect two strings, and merge two lists. Because the '+' operator is overloaded by the int and str classes, it is possible. This is known as Operator Overloading, and it occurs when the same built-in operator or method behaves differently for objects of various types. Procedure to overload operator in python: Consider the following scenario: we have two objects that are physical representations of a class (user-defined data type), and we need to add them together using the binary '+' operator. The compiler will raise an error since it does not know how to add two objects. Operator overloading is the process of defining a method for an operator. All current operators can be overloaded, but we can't construct a new one. Python offers a custom function or magic function for operator overloading that is automatically executed when it is connected with a certain operator. When we use the + operator, for example, the magical method __add__ is immediately called, which defines the + operator's operation. Page 22 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 23 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 4.11Any & All in python Any and All are two built-ins in Python that are used to perform sequential And/Or. These built-in methods any() and all() have been around since the introduction of Python 2.5. • Any: If any of the elements are true, this method returns true. If the array is empty or all of the values are false, it returns False. Any may be seen as a series of OR operations just on iterables given. It stops the execution as immediately as the result is known, thus short- circuiting it. • All: If all of the elements are True, this function returns true (or if the iterable is empty). All of these procedures may be seen as a series of AND operations just on given iterables. It also shorts circuits the execution, stopping it as soon as the outcome is known. Example: Page 24 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output 4.12 Summary • In Python, operators are special symbols that perform arithmetic or logical computations. • In Python, Addition, subtraction, multiplication, and other mathematical operations are performed using arithmetic operators. • In Python, Values are compared using comparison operators. Depending on the criteria, it returns True or False. • In Python, the and, or, and not operators are logical operators. • In Python, Bitwise operators treat operands as though they were binary digit strings. They work in little increments, thus the name. • In Python, to assign values to variables in Python, assignment operators are employed. Page 25 of 26 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics • In Python, the identity and membership operators are two specific sorts of operators available in the Python language. • In Python, the membership operators are used to see if a value or variable exists in a sequence (string, list, tuple, set and dictionary). 4.13 Glossary • Overloading: The ability to construct many functions with the same name but distinct implementations is known as function overloading or method overloading. • Boolean: It's a data type with one of two potential values (typically labelled true and false) that's meant to reflect logic's and Boolean algebra's two truth values. • Operand: It's the component of a computer programme that describes what data should be changed or worked on while also describing the data itself. 4.14 References • https://docs.python.org/3/ • https://docs.python.org/3/library/operator.html • https://github.com/python/cpython/blob/3.10/Lib/operator.py • https://docs.python.org/3/library/operator.html#mapping- operators-to-functions • https://docs.python.org/3/library/operator.html#in-place-operators Page 26 of 26 All Rights Reserved. Vol. TLE001/03-2022


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook