Arithmetic Expressions in Python
What is Python Expression?
Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up of both operators and operands.
An illustration of an expression is x = x + 5. The variable x is increased by the first 5 in this expression. The outcome of the addition is then allocated to the variable x.
Example:
x=10; //statement
x=x+5; // Expression
print(x);
Output:
15
Python statements and expressions are significantly distinct from one another. Some findings do not assess a statement. A statement is used to declare variables and to show their values.
In Python, identifiers, operators, and operands can all be found in expressions. Let's talk about them briefly.
Identifier
An identifier is a name used to identify a variable, function, class, module or other objects in Python. It can be any combination of letters, numbers, and underscores. It must start with a letter or underscore, and cannot contain spaces or other special characters. Identifiers are often used to refer to variables, functions, or classes within a program.
There are a few rules that you need to follow when using identifiers in Python:
- Identifiers are case-sensitive, so myVariable and myvariable are considered to be different identifiers.
- Python has a set of reserved words that cannot be used as identifiers. These reserved words include ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘False’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘None’, ‘nonlocal’, ‘raise’, ‘return’, ‘True’,‘not’, ‘or’, ‘pass’, ‘try’, ‘while’, and ‘with’.
- Identifiers cannot contain any spaces.
- Identifiers cannot start with a digit.
Here are some examples of valid identifiers in Python:
Example Code:
my_variable
_private_variable
__double_underscore_variable
SomeClass
some_function
Operand
In Python, an operand is a value or object on which an operator acts. Operands are typically variables, constants, or expressions, and are often used in conjunction with operators to form expressions.
For example, in the expression “4 + 6,” the operands are ‘4’ and ‘6’, and the operator is ‘+’. In this case, the operator ‘+’ adds the two operands together to produce a result of ‘10’.
Operator
In Python, an operator is a symbol that represents an operation to be performed on one or more operands. Operators are used to perform calculations, comparisons, and other operations on operands in expressions and statements.
There are several types of operators in Python, including arithmetic operators, assignment operators, comparison operators, logical operators, and bitwise operators.
Python has many different types of operators, some of which are listed below:
- + addition operator
- - subtraction operator
- * multiplication operator
- / division operator
- // floor division operator
- % modulus operator (returns the remainder of a division operation)
- ** exponentiation operator
- = assignment operator
- += augmented assignment operator (adds the right operand to the left operand and assigns the result to the left operand)
- -= augmented assignment operator (subtracts the right operand from the left operand and assigns the result to the left operand)
- *= augmented assignment operator (multiplies the left operand by the right operand and assigns the result to the left operand)
- /= augmented assignment operator (divides the left operand by the right operand and assigns the result to the left operand)
- //= augmented assignment operator (performs floor division on the left operand by the right operand and assigns the result to the left operand)
- %= augmented assignment operator (performs modulus on the left operand by the right operand and assigns the result to the left operand)
- **= augmented assignment operator (raises the left operand to the power of the right operand and assigns the result to the left operand)
- == equal to operator
- != not equal to operator
- < less than operator
- > greater than operator
- <= less than or equal to operator
- >= greater than or equal to operator
- and (logical and operator)
- or (logical or operator)
- not (logical not operator)
- & bitwise and operator
- | bitwise or operator
- ^ bitwise xor operator
- ~ bitwise not operator
- << bitwise left shift operator
- >> bitwise right shift operator
Types of Expression in Python
In Python, an expression is a logical block of code that is evaluated to produce a certain result. When there are many operators in an expression, the operators are resolved according to their order of precedence.
There are several forms of expression in Python. Let’s learn about them.
1. Constant Expressions
A constant expression is a piece of code that can be evaluated at compile time, rather than at runtime. This means that the value of the expression can be determined before the program is executed, and it will not change during the course of the program's execution.
In Python, there are a few distinct forms of expressions that can be termed constant:
(i) Literals:
These are all constant expressions because they are fixed values written directly into the code.
Example:
5 integer literal
3.14 float literal
"hello" string literal
True Boolean literal
(ii) Identifiers:
These are all constant expressions because the values of the identifiers do not change.
Example:
x = 5 x is a constant expression because its value does not change.
y = "hello" y is a constant expression because its value does not change.
def func(): func is a constant expression because it only consists of constant expressions and does not change any global state.
(iii) Operators:
These are all constant expressions because the operands are constant expressions.
Example:
5 + 3 addition operator
3.14 * 2 multiplication operator
"hello" + "world" concatenation operator
(iv) Functions:
This is a constant expression because it only consists of constant expressions and does not change any global state.
Example:
def func():
return 5 + 3
Constant expressions can be useful in a variety of situations, such as optimizing code performance by avoiding unnecessary calculations, or ensuring that certain values are always consistent throughout a program.
It's important to note that while Python does not have a built-in concept of constants; it is possible to create the appearance of constants by using naming conventions, such as using all uppercase letters for the names of variables that should not be modified. However, it's still possible to change the value of these variables if desired.
2. Integral Expressions
An integral expression is an expression that evaluates to an integer value. As a consequence of an integral expression, the result is always an integer value.
There are several types of expressions that can be considered integral in Python, including:
(i) Literals:
These are all integral expressions because they are fixed integer values written directly into the code.
Example:
5 integer literal
-3 integer literal
0 integer literal
(ii) Identifiers:
These are all integral expressions because the values of the identifiers are integers.
Example:
x = 5 x is an integral expression because its value is an integer.
y = -3 y is an integral expression because its value is an integer.
def func(): func is an integral expression because it only consists of integral expressions and does not change any global state.
(iii) Operators:
These are all integral expressions because the operands are integral expressions.
Example:
5 + 3 addition operator
3 - 2 subtraction operator
4 * 2 multiplication operator
(iv) Functions:
This is an integral expression because it only consists of integral expressions and does not change any global state.
Example:
def func():
return 5 + 3
Integral expressions are often used in Python when working with integer values, such as in arithmetic operations or when indexing lists or arrays. It's important to note that Python also has a built-in data type called ‘int’ that can be used to represent integers.
3. Floating Expressions
A floating expression is an expression that evaluates to a floating-point value. A floating expression always yields a floating-point number as a result.
There are several types of expressions that can be considered floating in Python, including:
(i) Literals:
These are all floating expressions because they are fixed floating-point values written directly into the code.
Example:
3.14 float literal
0.1 float literal
-1.5 float literal
(ii) Identifiers:
These are all floating expressions because the values of the identifiers are floating-point numbers.
Example:
x = 3.14 x is a floating expression because its value is a floating-point number.
y = 0.1 y is a floating expression because its value is a floating-point number.
def func(): func is a floating expression because it only consists of floating expressions and does not change any global state.
(iii) Operators:
These are all floating expressions because the operands are floating expressions..
Example:
3.14 + 2.718 addition operator
4.5 - 1.2 subtraction operator
6.7 * 8.9 multiplication operator
(iv) Functions:
This is a floating expression because it only consists of floating expressions and does not change any global state.
Example:
def func():
return 3.14 + 2.718
Floating expressions are often used in Python when working with decimal values, such as in arithmetic operations or when representing quantities with a certain level of precision. It's important to note that Python also has a built-in data type called ‘float’ that can be used to represent floating-point numbers.
4. Relational Expressions
A relational expression in Python compares two values and gives output a Boolean value indicating whether the comparison is accurate or inaccurate. In Python, there are various kinds of relational expressions, including:
(i) Equality:
These are all relational expressions that test for equality.
Example:
5 == 3 returns False because 5 is not equal to 3.
"hello" == "world" returns False because "hello" is not equal to "world".
True == True returns True because True is equal to True.
(ii) Inequality:
These are all relational expressions that test for inequality.
Example:
4 != 9 returns True because 4 is not equal to 9.
"hello" != "world" returns True because "hello" is not equal to "world".
True != False returns True because True is not equal to False.
(iii) Less than:
These are all relational expressions that test for less than.
Example:
5 < 3 returns False because 5 is not less than 3.
-1 < 0 returns True because -1 is less than 0.
"a"<"b" returns True because "a" is less than "b".
(iv) Greater than:
These are all relational expressions that test for greater than.
Example:
5 > 3 returns True because 5 is greater than 3.
-1 > 0 returns False because -1 is not greater than 0.
"z">"a" returns True because "z" is greater than "a".
(v) Less than or equal to:
These are all relational expressions that test for less than or equal to.
Example:
2 <= 5 returns False because 2 is not less than or equal to 5.
-1 <= 0 returns True because -1 is less than or equal to 0.
"a"<= "b" returns True because "a" is less than or equal to "b".
(vi) Greater than or equal to:
These are all relational expressions that test for greater than or equal to.
Example:
5 >= 3 returns True because 5 is greater than or equal to 3.
-1 >= 0 returns False because -1 is not greater than or equal to 0.
"z">= "a" returns True because "z" is greater than or equal to "a".
Relational expressions are often used in Python to compare values and make decisions based on the results of the comparison. They can be used in a variety of contexts, such as in control statements like ‘if’ and ‘while’, or in Boolean expressions like ‘and’ and ‘or’.
5. Logical Expressions
A logical expression in Python is a statement that combines two or more Boolean values with logical operators and outputs a Boolean value that represents the outcome of the operation. Python supports three different types of logical expressions:
(i) Logical AND:
These are all logical AND expressions that test whether both Boolean values are True.
Example:
True and True: returns True because both Boolean values are True.
False and True: returns False because one of the Boolean values is False.
True and False: returns False because one of the Boolean values is False.
False and False: returns False because both Boolean values are False.
(ii) Logical OR:
These are all logical OR expressions that test whether at least one of the Boolean values is True.
Example:
True or True: returns True because at least one of the Boolean values is True.
False or True: returns True because at least one of the Boolean values is True.
True or False: returns True because at least one of the Boolean values is True.
False or False: returns False because neither of the Boolean values is True.
(iii) Logical NOT:
These are all logical NOT expressions that negate the Boolean value.
Example:
not True: returns False because it negates the Boolean value True.
not False: returns True because it negates the Boolean value False.
Logical expressions are often used in Python to make decisions based on multiple conditions, or to negate the value of a Boolean expression. They can be used in a variety of contexts, such as in control statements like ‘if’ and ‘while’, or in Boolean expressions like ‘and’ and ‘or’.
It's important to note that in Python, the values ‘True’ and ‘False’ are Boolean values, and they are written with a capital T and F respectively. Boolean values are often used in conjunction with logical expressions to make decisions in a program.
6. Bitwise Operators
A bitwise expression in Python is a statement that applies bitwise operations to integer numbers. Bitwise operations are operations that change each bit in a number's binary representation. In Python, there are various kinds of bitwise expressions, including:
(i) Bitwise AND:
These are all bitwise AND expressions that perform a bitwise AND operation on two integer values.
Example:
5 & 3: returns 1 because the binary representation of 5 is 101 and the binary representation of 3 is 011, and the result of the bitwise AND operation is 001, which is the binary representation of 1.
7 & 9: returns 1 because the binary representation of 7 is 111 and the binary representation of 9 is 1001, and the result of the bitwise AND operation is 001, which is the binary representation of 1.
10 & 5: returns 0 because the binary representation of 10 is 1010 and the binary representation of 5 is 101, and the result of the bitwise AND operation is 0000, which is the binary representation of 0.
(ii) Bitwise OR:
These are all bitwise OR expressions that perform a bitwise OR operation on two integer values.
Example:
5 | 3: returns 7 because the binary representation of 5 is 101 and the binary representation of 3 is 011, and the result of the bitwise OR operation is 111, which is the binary representation of 7.
7 | 9: returns 15 because the binary representation of 7 is 111 and the binary representation of 9 is 1001, and the result of the bitwise OR operation is 1111, which is the binary representation of 15.
(iii) Bitwise XOR:
This is a bitwise XOR expression that performs a bitwise XOR operation on two integer values.
Example:
5 ^ 3 returns 6 because the binary representation of 5 is 101 and the binary representation of 3 is 011, and the result of the bitwise XOR operation is 110, which is the binary representation of 6.
(iv) Bitwise NOT:
This is a bitwise NOT expression that negates the integer value.
Example:
~5: returns -6 because the binary representation of 5 is 101, and the result of the bitwise NOT operation is 010, which is the binary representation of -6
7. Arithmetic Expressions:
An arithmetic expression in Python consists of a set of numeric numbers and operators that all evaluate to a single value.
Arithmetic expressions can include a variety of operators, including the addition, subtraction, multiplication, and division operations that are commonly used in mathematics. Python also has the modulo operator (%) and the exponentiation operator (**) for raising an integer to a power and calculating the remainder of a division operation, respectively.
(i) Addition:
These expressions add two or more numerical values together. The addition operator in Python is ‘+’.
Example 1:
x = 2
y = 3
result = x + y
print(result) prints 5
Example 2:
// Using Floating Point Numbers
x = 4.5
y = 6.7
result = x + y
print(result) prints 11.2
You can also use it to concatenate string variables like this:
Example 3:
string1 = "Hello"
string2 = "world"
result = string1 + "" + string2
print(result) prints "Hello world"
(ii) Subtraction:
These expressions subtract one numerical value from another. The subtraction operator in Python is ‘-’.
Example 1:
x = 10
y = 5
result = x - y
print(result) prints 5
Example 2:
// Using Floating Point Numbers
x = 9.8
y = 4.5
result = x - y
print(result) prints 5.3
(iii) Multiplication:
These expressions multiply two or more numerical values together. The multiplication operator in Python is ‘*’.
Example 1:
x = 2
y = 3
result = x * y
print(result) prints 6
Example 2:
// Using Floating Point Numbers
x = 4.5
y = 6.7
result = x * y
print(result) prints 30.15
(iv) Division:
These expressions divide one numerical value by another. The division operator in Python is ‘/’.
Example 2:
x = 10
y = 5
result = x / y
print(result) prints 2.0
Example 2:
// Using Floating Point Numbers
x = 9.8
y = 4.5
result = x / y
print(result) prints 2.177777777777778
(v) Modulo:
These expressions divide one numerical value by another and return the remainder of a division operation. The modulus operator in python is ‘%’.
Example 1:
x = 17
y = 3
result = x % y
print(result) prints 2
Note: Floating-point numbers should be handled with carefully. You will need to convert them to integers or use another technique to execute the operation because the modulo operator does not operate with floating-point numbers.
(vi) Exponentiation:
These expressions raise one numerical value to the power of another. The exponentiation operator in Python is ‘**’.
Example 1:
x = 2
y = 3
result = x ** y
print(result) prints 8
Example 2:
// Using Floating Point Numbers
x = 4.5
y = 6.7
result = x ** y
print(result) prints 236.01166894017546
Things to be remembered while using with arithmetic expressions
Python follows the standard order of operations (also known as the "PEMDAS" rule) when evaluating arithmetic expressions. This indicates that evaluation of parentheses comes first, followed by exponentiation, left-to-right multiplication and division, and then addition and subtraction (also performed from left to right).
In addition to the basic arithmetic operators, a variety of functions and techniques are also available in Python for carrying out more complex mathematical calculations. For example, the ‘math’ module provides functions for computing trigonometric functions, logarithms, and other common mathematical operations.
Conclusion:
Arithmetic expressions are an important part of Python programming, allowing you to perform a wide range of mathematical operations using numbers, variables, and operators. With its support for a range of number types and arithmetic operators, as well as advanced functions and methods for more complex calculations, Python provides everything you need to work with arithmetic expressions effectively. Whether you're a beginner or an experienced programmer, understanding how to use arithmetic expressions in Python will be an important part of your toolkit.