Comments

Tutorials

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 − Open Compiler Python supports three types of comments as shown below − 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 “− Open Compiler 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 − Open Compiler Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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 − Open Compiler 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 − Open Compiler 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 Python’s built-in documentation tools. Example of a Function Docstring Open Compiler 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 Open Compiler Example: Using the help() Function Open Compiler

October 3, 2024 / 0 Comments
read more

Python Operator Precedence

Tutorials

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 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)? Python’s 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: 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, 3 await 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 12 in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests 13 not xBoolean NOT 14 andBoolean AND 15 orBoolean OR 16 if – elseConditional expression 17 lambdaLambda expression 18 :=Walrus operator Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python Operator Precedence Example Open Compiler When you execute the above program, it produces the following result −

October 3, 2024 / 0 Comments
read more

Identity Operators

Tutorials

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: 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 Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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 Open Compiler It will produce the following output − Python Identity Operators Examples with Explanations Example 1 Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − 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 It will produce the following output − Because of two different locations of “a” and “b”, the “is” operator returns False even if the two lists contain same numbers.

October 3, 2024 / 0 Comments
read more

Membership Operators

Tutorials

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. Open Compiler It will produce the following output − 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, list, tuple, etc. Example of Python Membership “not in” Operator Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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. Open Compiler It will produce the following output − 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. 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. Open Compiler It will produce the following output − Membership Operator with Sets Python’s membership operators also work well with the set objects. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Python – Bitwise Operators

Tutorials

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 – 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 − 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. Open Compiler It will produce the following output − To understand how Python performs the operation, obtain the binary equivalent of each variable. It will produce the following output − 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. Convert the resultant binary back to integer. You’ll get 12, which was the result obtained earlier. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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. 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. Open Compiler It will produce the following output − To perform the “|” operation manually, use the 8-bit format. Convert the binary number back to integer to tally the result − 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. Example of Bitwise XOR Operator in Python Let us perform XOR operation on a=60 and b=13. Open Compiler It will produce the following output − We now perform the bitwise XOR manually. The int() function shows 00110001 to be 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) Example of Bitwise NOT Operator in Python For a=60, its complement is − Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − How does this take place? Let us use the binary equivalent of 60, and perform the left shift by 2. Convert the binary to integer. It is 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. Open Compiler It will produce the following output − Manual right shift operation on 60 is shown below − Use int() function to covert the above binary number to integer. It is 15.

October 3, 2024 / 0 Comments
read more

 Logical Operators

Tutorials

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 Along with the keyword False, Python interprets None, numeric zero of all types, and empty sequences (strings, tuples, lists), 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. a b a and b F F F F T F T F F T T T Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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: a b a or b F F F F T T T F T T T T 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 a not (a) F T T F 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. 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. Python Logical Operators Examples Some use cases of logical operators are given below − Example 1: Logical Operators With Boolean Conditions Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Assignment Operators

Tutorials

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 − 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 (+=) Following examples will help in understanding how the “+=” operator works − Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Comparison Operators

Tutorials

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 than a<b > Greater than a>b <= Less than or equal to a<=b >= Greater than or equal to a>=b == Is equal to a==b != Is not equal to a!=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 Open Compiler It will produce the following output − Both the operands may be Python literals, variables 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 − Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Comparison of Float Number In the following example, an integer and a float operand are compared. Example Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − You get a TypeError with less than or greater than operators. Example Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − In the following example, two tuple objects are compared − Example Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Arithmetic Operators

Tutorials

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: Operator Name Example + Addition a + b = 30 – Subtraction a – b = -10 * Multiplication a * b = 200 / Division b / a = 2 % Modulus b % a = 0 ** Exponent a**b =10**20 // Floor Division 9//2 = 4 Let us study these operators with examples. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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. Open Compiler It will produce the following output − Example to add integer and float numbers Addition of integer and float results in a float. Open Compiler It will produce the following output − Example to add two complex numbers The result of adding float to complex is a complex number. Open Compiler It will produce the following output − 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. Open Compiler Result − Example to subtract integer and float numbers Subtraction of an integer and a float follows the same principle. Open Compiler It will produce the following output − Example to subtract complex numbers In the subtraction involving a complex and a float, real component is involved in the operation. Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − Example to multiply integer and float numbers In multiplication, a float operand may have a standard decimal point notation, or a scientific notation. Open Compiler It will produce the following output − Example to multiply complex numbers For the multiplication operation involving one complex operand, the other operand multiplies both the real part and imaginary part. Open Compiler It will produce the following output − 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 Open Compiler It will produce the following output − Example to divide two float numbers In Division, a float operand may have a standard decimal point notation, or a scientific notation. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − Example for modulus operation on floats If any of the operands is a float, the mod value is always float. Open Compiler It will produce the following output − Python doesn’t accept complex numbers to be used as operand in modulus operation. It throws TypeError: unsupported operand type(s) for %. Exponent Operator Python uses ** (double asterisk) as the exponent operator (sometimes called raised to operator). So, for a**b, you say a raised to b, or even bth power of a. If in the exponentiation expression, both operands are integer, result is also an integer. In case either one is a float, the result is float. Similarly, if either one operand is complex number, exponent operator returns a complex number. If the base is 0, the result is 0, and if the index is 0 then the result is always 1. Example of exponent operator Open Compiler It will produce the following output − Floor Division Operator Floor division is also called as integer division. Python uses // (double forward slash) symbol for the purpose. Unlike the modulus or modulo which returns the remainder, the floor division gives the quotient of the division of operands involved. If both operands are positive, floor operator returns a number with fractional

October 3, 2024 / 0 Comments
read more

Operators

Tutorials

Python Operators Python operators are special symbols used to perform specific operations on one or more operands. The variables, values, or expressions can be used as operands. For example, Python’s addition operator (+) is used to perform addition operations on two variables, values, or expressions. The following are some of the terms related to Python operators: Types of Python Operators Python operators are categorized in the following categories − Let us have a look at all the operators one by one. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python Arithmetic Operators Python Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, etc. The following table contains all arithmetic operators with their symbols, names, and examples (assume that the values of a and b are 10 and 20, respectively) − Operator Name Example + Addition a + b = 30 – Subtraction a – b = -10 * Multiplication a * b = 200 / Division b / a = 2 % Modulus b % a = 0 ** Exponent a**b =10**20 // Floor Division 9//2 = 4 Example of Python Arithmetic Operators Open Compiler Output Python Comparison Operators Python Comparison operators compare the values on either side of them and decide the relation among them. They are also called Relational operators. The following table contains all comparison operators with their symbols, names, and examples (assume that the values of a and b are 10 and 20, respectively) − Operator Name Example == Equal (a == b) is not true. != Not equal (a != b) is true. > Greater than (a > b) is not true. < Less than (a < b) is true. >= Greater than or equal to (a >= b) is not true. <= Less than or equal to (a <= b) is true. Example of Python Comparison Operators Open Compiler Output Python Assignment Operators Python Assignment operators are used to assign values to variables. Following is a table which shows all Python assignment operators. The following table contains all assignment operators with their symbols, names, and examples − Operator Example Same As = a = 10 a = 10 += a += 30 a = a + 30 -= a -= 15 a = a – 15 *= a *= 10 a = a * 10 /= a /= 5 a = a / 5 %= a %= 5 a = a % 5 **= a **= 4 a = a ** 4 //= a //= 5 a = a // 5 &= a &= 5 a = a & 5 |= a |= 5 a = a | 5 ^= a ^= 5 a = a ^ 5 >>= a >>= 5 a = a >> 5 <<= a <<= 5 a = a << 5 Example of Python Assignment Operators Open Compiler Output Python Bitwise Operators Python Bitwise operator works on bits and performs bit by bit operation. These operators are used to compare binary numbers. The following table contains all bitwise operators with their symbols, names, and examples − Operator Name Example & AND a & b | OR a | b ^ XOR a ^ b ~ NOT ~a << Zero fill left shift a << 3 >> Signed right shift a >> 3 Example of Python Bitwise Operators Open Compiler Output Python Logical Operators Python logical operators are used to combile two or more conditions and check the final result. There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then The following table contains all logical operators with their symbols, names, and examples − Operator Name Example and AND a and b or OR a or b not NOT not(a) Example of Python Logical Operators Open Compiler Output Python Membership Operators Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below − Operator Description Example in Returns True if it finds a variable in the specified sequence, false otherwise. a in b not in returns True if it does not finds a variable in the specified sequence and false otherwise. a not in b Example of Python Membership Operators Open Compiler Output Python Identity Operators Python identity operators compare the memory locations of two objects. There are two Identity operators explained below − Operator Description Example is Returns True if both variables are the same object and false otherwise. a is b is not Returns True if both variables are not the same object and false otherwise. a is not b Example of Python Identity Operators Open Compiler Output Python Operators Precedence Operators precedence decides the order of the evaluation in which an operator is evaluated. Python operators have different levels of precedence. The following table contains the list of operators having highest to lowest precedence − The following table lists all operators from highest precedence to lowest. Sr.No. Operator & Description 1 **Exponentiation (raise to the power) 2 ~ + –Complement, unary plus and minus (method names for the last two are +@ and -@) 3 * / % //Multiply, divide, modulo and floor division 4 + –Addition and subtraction 5 >> <<Right and left bitwise shift 6 &Bitwise ‘AND’ 7 ^ |Bitwise exclusive OR’ and regular OR’ 8 <= < > >=Comparison operators 9 <> == !=Equality operators 10 = %= /= //= -= += *= **=Assignment operators 11 is is notIdentity operators 12 in not inMembership operators 13 not or andLogical operators Read more about the Python operators precedence here: Python operators precedence

October 3, 2024 / 0 Comments
read more

Posts pagination

Previous 1 … 15 16 17 18 Next