Expressions in Python
An expression in Python is any valid combination of values, variables, operators,
that can be evaluated (executed) to produce a result.
an expression is a piece of code that computes a value when executed.
Expressions are a fundamental building block of programming because they
define the logic of operations and computations.
Types of Expressions in Python
Constant Expressions:
A constant expression in Python that contains only constant values is known as a
constant expression.
A constant is a value that cannot be changed
Example –
# Constant Expressions
x = 15 + 1.3
print(x)
Arithmetic Expressions
Perform mathematical operations.
An expression in Python that contains a combination of operators, operands, and
sometimes parenthesis is known as an arithmetic expression.
Example
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
print("The sum of x and y is: ", addition)
print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
Relational Expressions:
Compare values and return a boolean (True or False)
A relational operator produces a boolean result so they are also known as Boolean
Expressions.
We have four types of relational operators in Python (i.e.>,<,>=,<=)
(i.e.>,<,>=,<=).
== Equal to
!= Not equal to
>: Greater than
>= Greater than or equal to
<= Less than or equal to
<: Less than
Example 1
a = 10 b = 20
comparison = a < b # Evaluates to True
example 2
a=9
b=5
c=9
print(a <= b)
print(a <= c)
print(b <= a)
False
True
True
Logical Expressions
a logical expression performs the logical computation, and the overall expression
results in either True or False (boolean result). We have three types of logical
expressions in Python
Operator Syntax Working
x and The expression return True if both x and y are true, else it
and
y returns False.
or x or y The expression return True if at least one of x or y is True.
not not x The expression returns True if the condition of x is False
Example
x = 10
y=5
z = 15
# Logical expressions using relational expressions
print((x > y) and (z > x)) # True, because both conditions are True
print((x < y) or (z > x)) # True, because one condition is True
print(not (x > y)) # False, because the condition (x > y) is True, and `not` negates it