Here is a clear, detailed, and exam-oriented explanation of Expressions in Python, perfect for BCA/MCA/B.Tech students.
Expressions in Python
An expression in Python is a combination of:
- values
- variables
- operators
- function calls
…that Python evaluates to produce a result (a value).
Simply, an expression is anything that returns a value.
1. Examples of Expressions
Arithmetic Expression
5 + 3
Returns:
8
Variable Expression
x = 10
x + 20
Boolean Expression
10 > 5
Returns:
True
String Expression
"Hello " + "World"
Returns:
"Hello World"
2. Types of Expressions in Python
Python supports several types of expressions:
1. Arithmetic Expressions
Involve mathematical operations.
Examples:
a = 10
b = 3
c = a + b * 2 # 10 + 6 = 16
2. Relational (Boolean) Expressions
Used in conditions — always return True or False.
Examples:
x = 5
y = 10
print(x < y) # True
print(x == y) # False
3. Logical Expressions
Use logical operators (and, or, not).
Examples:
x = 10
print(x > 5 and x < 20) # True
print(not x == 10) # False
4. String Expressions
Use + and * with strings.
Examples:
"Hello " + "Python"
"Ha" * 3 # HaHaHa
5. Assignment Expressions
Use assignment operators (=, +=, -=, etc.).
Example:
x = 10 # assignment expression
x += 5 # x = x + 5
6. Bitwise Expressions
Operate on bits using operators like &, |, ^.
Example:
5 & 3
7. Function Call Expressions
A function call is also an expression because it returns a value.
Example:
len("Hello") # returns 5
max(10, 20)
8. List, Dictionary, Tuple Expressions
Examples:
[1, 2, 3] # list expression
(1, 2, 3) # tuple expression
{"a": 1} # dictionary expression
3. Expression vs Statement
This is a common exam question.
| Expression | Statement |
|---|---|
| Always returns a value | Performs an action |
| Can be part of a statement | Cannot always return a value |
Example: 5 + 3 | if, for, while, function definition |
Example:
x = 5 + 3 # Statement that contains an expression
4. Compound Expressions
Expressions can be combined using parentheses:
Example:
result = (10 + 5) * 3 / 5
5. Operator Precedence in Expressions
Expression execution follows specific rules:
- Parentheses
() - Exponent
** - Unary
+,- *, /, %, //+, -- Comparisons
- Logical
- Assignment
Example:
x = 10 + 5 * 2 # 5*2 = 10 → 10+10 = 20
6. Evaluating Expressions
Use the eval() function to evaluate expressions given as a string.
Example:
eval("10 + 5 * 2")
Output:
20
7. Examples of Python Expressions
Example 1:
num = 7
print(num * 2 + 3)
Example 2:
x = 10
y = 20
print(x > 5 and y < 30)
Example 3:
name = "Python"
print("I love " + name)
Summary
- An expression is anything that returns a value.
- Python expressions include arithmetic, logical, relational, string, bitwise, and function call expressions.
- Expressions follow operator precedence rules.
- Expressions can be nested or combined.
- Difference between expression and statement is important for exams.
