Expressions in Python: Types, Examples, and How They're Evaluated
TL;DR: An expression in Python is any piece of code that produces a value, such as 2 + 3, x > 10, or len(name). Python supports many kinds of expressions, including arithmetic, relational, logical, bitwise, conditional, assignment, lambda, and generator expressions. When an expression mixes operators, Python applies them in a fixed order called operator precedence, and parentheses let you override it. Knowing these rules helps you write code that computes exactly what you intend.

Expressions are the building blocks of every Python program. Each time you add two numbers, compare values, call a function, or build a list, you're writing an expression. They combine operators, variables, literals, and function calls to produce a value, which you can then store, print, pass to a function, or use in a larger expression.

This guide explains expressions in Python with runnable examples and their real output. You'll learn every major type of expression, how expressions differ from statements, and how Python decides which part of an expression to evaluate first.

What Is an Expression in Python?

An expression combines values, variables, operators, and function calls that Python can evaluate to produce a single value. 42 is an expression, and so are price * quantity, age >= 18, and len("Python"). If you can print it or assign it to a variable, it's an expression.

price = 250
quantity = 4

print(price * quantity)          # arithmetic expression
print(price > 200)               # relational expression
print(len("Python") + 1)         # function call inside an expression
print("Py" + "thon")             # string expression

Output:

1000
True
7
Python

Expressions in Python serve different purposes. Arithmetic expressions calculate numbers, relational expressions compare values and return True or False, and logical expressions combine conditions with and, or, and not to drive decisions in your code.

With the Python Certification CourseENROLL NOW
Deep Dive Into Core Python Concepts

Statements vs Expressions in Python

Statements and expressions in Python work together, but they aren't the same thing. A statement is a complete instruction that tells Python to do something, such as assign a variable, run a loop, or import a module. An expression is code that produces a value. Many statements contain expressions: in result = x * 2, the whole line is an assignment statement, and x * 2 is the expression inside it.

x = 5              # statement: assigns a value, produces nothing
result = x * 2     # x * 2 is an expression; the whole line is a statement
print(result)

# An expression can go anywhere a value is expected
print(max(x, 3) + 10)

# An assignment statement cannot be used where a value is expected
try:
    compile("y = (x = 5)", "<test>", "exec")
except SyntaxError as e:
    print("SyntaxError:", e.msg)

Output:

10
15
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Expression

Statement

What it does

Produces a value

Performs an action

Examples

3 + 4, x > 5, len(items), "a" if ok else "b"

x = 5, if, for, while, def, import, return

Can be assigned or passed to a function

Yes

No

Can contain the other

Can't contain statements

Often contains expressions

Examples

3 + 4, x > 5, len(items)

x = 5, if, for, import

An expression on its own line, such as print("hi"), is also a valid statement, called an expression statement. The walrus operator:=, covered below, is the exception that lets you assign a value inside an expression.

Python Certification CourseENROLL NOW
Master Web Scraping, Django, Operators, & Sets

Types and Forms of Expressions in Python

Python expressions are usually grouped by the operators they use or the kind of value they produce:

Type of expression

What it does

Example

Constant

Uses only fixed values

10 + 1.3

Arithmetic

Performs math

a * b + c

Integral

Produces an integer

15 + int(11.0)

Floating

Produces a float

11 / 2

Relational

Compares values

age >= 18

Logical

Combines conditions

x > 0 and y > 0

Bitwise

Works on binary digits

a & b

Identity and membership

Checks object identity or containment

x is None, "a" in word

Combinational

Mixes several operator types

a + (b >> 1)

Conditional

Chooses between two values

"Pass" if marks >= 40 else "Fail"

Assignment

Assigns and returns a value

(n := len(data))

Lambda

Creates a small anonymous function

lambda x: x * 2

Comprehension and generator

Builds a sequence

[n * n for n in nums]

Function calls such as len() or max() can appear inside any of these. To learn how to write your own, see this guide to Python functions.

Also Read: Python If-Else Statement 

Constant Expressions

A constant expression contains only fixed values, such as number or string literals, so it always produces the same result when the program runs.

# Constant Expressions
a = 10 + 1.3

print(a)

Output:

11.3

Arithmetic Expressions

An arithmetic expression combines numbers, arithmetic operators, and sometimes parentheses to produce a numeric result. Python has seven arithmetic operators:

Name

Operator

Syntax

Example result

Addition

+

x + y

10 + 5 gives 15

Subtraction

-

x - y

10 - 5 gives 5

Multiplication

*

x * y

3 * 5 gives 15

Division

/

x / y

7 / 3 gives 2.333...

Modulus (remainder)

%

x % y

10 % 5 gives 0

Exponentiation (double asterisk)

**

x ** y

9 ** 3 gives 729

Floor division

//

x // y

15 // 4 gives 3

a = 10
b = 5
print(a + b)    # Addition

a = 10
b = 5
print(a - b)    # Subtraction

a = 3
b = 5
print(a * b)    # Multiplication

a = 7
b = 3
print(a / b)    # Division always returns a float

a = 10
b = 5
print(a % b)    # Modulus: remainder of 10 / 5

a = 9
b = 3
print(a ** b)   # Exponentiation: 9 to the power 3

a = 15
b = 4
print(a // b)   # Floor division

Output:

15
5
15
2.3333333333333335
0
729
3

Notice that / always returns a float, even when the numbers divide evenly, while // drops the fractional part. If you mix an integer and a float in one expression, Python converts the result to a float.

AI-Powered Full Stack Developer ProgramExplore Program
Want a Top Software Development Job? Start Here!

Integral Expressions

An integral expression produces an integer after all the calculations and type conversions are done. Here, int() turns the float 11.0 into the integer 11 before the addition, so the result is an integer.

# Integral Expressions
a = 15
b = 11.0

c = a + int(b)
print(c)

Output:

26

Floating Expressions

A floating expression produces a floating-point number, a number with a decimal part such as 112.3 or 1345.92, as opposed to an integer such as 64. In Python 3, the / operator always produces a float.

# Floating Expressions
a = 11
b = 2

c = a / b
print(c)

Output:

5.5

Floats are stored in binary, so some decimal values can't be represented exactly. That's why 0.1 + 0.2 isn't exactly 0.3. When you compare floats, use math.isclose() or round the result.

import math

total = 0.1 + 0.2
print(total)
print(total == 0.3)
print(math.isclose(total, 0.3))
print(round(total, 2))

Output:

0.30000000000000004
False
True
0.3
AI-Powered Full Stack Developer ProgramExplore Program
Here's How to Land a Top Software Developer Job

Relational Expressions

A relational (or comparison) expression compares two values and always returns a Boolean, True or False. These expressions are what make conditions in if statements and loops work.

Meaning

Operator

Syntax

Equal to

==

x == y

Not equal to

!=

x != y

Greater than

>

x > y

Greater than or equal to

>=

x >= y

Less than

<

x < y

Less than or equal to

<=

x <= y

print(5 == 5)             # True
print(3 == 4)             # False
print("happy" != "happy") # False
print(8 != 9)             # True
print(4 > 2)              # True
print(2 > 9)              # False
print(9 >= 9)             # True
print(3 >= 8)             # False
print(1 < 6)              # True
print(9 < 4)              # False
print(1 <= 5)             # True
print(8 <= 3)             # False

Output:

True
False
False
True
True
False
True
False
True
False
True
False

Python also lets you chain comparisons. a < b < c means a < b and b < c, with b evaluated only once, which reads just like a range check in math.

age = 25

# Chained comparison: same as (18 <= age) and (age < 60)
print(18 <= age < 60)
print(1 < 2 > 3)   # (1 < 2) and (2 > 3)

Output:

True
False

Logical Expressions

Logical (or Boolean) expressions combine conditions with and, or, and not, and they're central to decision-making and control flow in Python.

Operator

Result

Syntax

and

True only if both operands are true

A and B

or

True if at least one operand is true

A or B

not

Reverses the truth value of its operand

not A

a = (14 == 5)
b = (8 > 4)

# Logical Expressions
P = a and b
Q = a or b
R = not a

print(P)
print(Q)
print(R)

Output:

False
True
True

Beginners often miss two details. First, and or short-circuit: Python stops evaluating as soon as the result is known, so the right side may never run. Second, it returns one of its operands rather than a plain True or False. Every value in Python is either "truthy" or "falsy" (0, "", [], and None are falsy), and it returns the first truthy operand, which makes it handy for default values.

# and / or return one of their operands, not always True or False
print(0 or "default")      # first operand is falsy, so "default" is returned
print("admin" and "ok")    # first operand is truthy, so "ok" is returned
print([] and "never")      # first operand is falsy, so [] is returned

# Short-circuiting: the right side is skipped when the answer is already known
count = 0
print(count != 0 and 10 / count > 1)   # no ZeroDivisionError

name = ""
print(name or "Guest")

Output:

default
ok
[]
False
Guest
Want to go further with Python? Simplilearn's Python training covers the language from fundamentals to real projects.

Bitwise Expressions

A bitwise expression works on integers at the level of their binary digits. Python converts each number to binary, applies the operation bit by bit, and gives you the result as a regular integer. Bitwise operators work only on integers.

Symbol

Name

Syntax

What it does

&

Bitwise AND

A & B

Each result bit is 1 only if both bits are 1

|

Bitwise OR

A | B

Each result bit is 1 if either bit is 1

~

Bitwise NOT

~A

Flips every bit; the result equals -(A + 1)

^

Bitwise XOR

A ^ B

Each result bit is 1 if the two bits differ

<<

Left shift

A << n

Shifts bits left by n places (multiplies by 2 to the power n)

>>

Right shift

A >> n

Shifts bits right by n places (floor-divides by 2 to the power n)

#bitwise AND
a = 9
b = 13
print(a & b)

#bitwise OR
a = 12
b = 6
print(a | b)

#bitwise NOT
a = 543
print(~a)

#bitwise XOR
a = 3
b = 10
print(a ^ b)

#bitwise left shift
a = 13
print(a << 1)
print(a << 3)

#bitwise right shift
a = 120
print(a >> 1)
print(a >> 3)

Output:

9
14
-544
9
26
104
60
15

~543 gives -544 because Python stores integers in two's complement form, where flipping all the bits of x produces -(x + 1).

Identity and Membership Expressions

Identity expressions use is and is not to check whether two names refer to the same object in memory. That's different from ==, which checks whether two values are equal. Membership expressions use in and not in to check whether a value appears in a sequence, set, or dictionary.

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)        # same values
print(a is b)        # different objects
print(a is c)        # same object
print(None is None)

print(2 in a)
print("z" not in "python")
print("name" in {"name": "Asha", "age": 30})   # checks dictionary keys

Output:

True
False
True
True
True
True
True

Use is mainly for comparisons with None, as in if result is None:, and use == to compare values.

AI-Powered Full Stack Developer ProgramExplore Program
Learn the In-Demand Development Skills!

Combinational Expressions

A combinational expression mixes different kinds of operators, such as arithmetic, relational, logical, and bitwise, in a single expression. Python works out the result by following operator precedence. In this example, the parentheses make the right shift happen first, so 12 >> 1 gives 6, and 15 + 6 gives 21.

# Combinational Expressions
a = 15
b = 12
c = a + (b >> 1)
print(c)

Output:

21

Conditional Expressions (Ternary Operator)

A conditional expression picks one of two values based on a condition, all on one line. Its syntax is value_if_true if condition else value_if_false. Because it's an expression, you can use it anywhere a value is expected, such as in an assignment, a function argument, or an f-string.

marks = 72

result = "Pass" if marks >= 40 else "Fail"
print(result)

# Conditional expressions can be used directly inside other expressions
print("Discount applied" if marks > 90 else "No discount")
print(abs(-5) if marks > 50 else 0)

Output:

Pass
No discount
5

Keep conditional expressions short. If the logic needs more than one condition, a regular if statement is easier to read.

Assignment Expressions (Walrus Operator)

Python 3.8 added the assignment expression, written with the := operator and nicknamed the walrus operator. It assigns a value to a variable and returns that value in the same step, so you can store a result while you're using it in a condition or a comprehension.

data = [4, 8, 15, 16, 23, 42]

# Assign and test in one step
if (n := len(data)) > 5:
    print(f"List is long: {n} items")

# Reuse a computed value inside a comprehension
values = [3, 7, 12]
doubled_big = [y for x in values if (y := x * 2) > 10]
print(doubled_big)

Output:

List is long: 6 items
[14, 24]

Without :=, the first example would need a separate line for n = len(data). The parentheses around the assignment expression are required in most places.

Lambda Expressions

A lambda expression creates a small, anonymous function in a single line. Its syntax is lambda arguments: expression. The function returns the value of that one expression automatically, with no return keyword.

square = lambda x: x ** 2
print(square(6))

add = lambda a, b: a + b
print(add(3, 4))

# Lambdas are most useful as short arguments to other functions
students = [("Ravi", 82), ("Meera", 95), ("Arjun", 67)]
print(sorted(students, key=lambda s: s[1], reverse=True))
print(list(filter(lambda s: s[1] >= 80, students)))

Output:

36
7
[('Meera', 95), ('Ravi', 82), ('Arjun', 67)]
[('Ravi', 82), ('Meera', 95)]

Lambdas work best as short, throwaway functions passed to other functions such as sorted(), filter(), and map(). For anything longer, define a normal function with def.

List Comprehensions and Generator Expressions

A list comprehension builds a new list from an existing sequence in one expression, using the form [expression for item in iterable if condition]. A generator expression uses the same syntax with parentheses instead of square brackets. Rather than building the whole list in memory, it produces values one at a time as you ask for them.

numbers = [1, 2, 3, 4, 5, 6]

# List comprehension: builds the whole list right away
squares = [n * n for n in numbers]
print(squares)

evens = [n for n in numbers if n % 2 == 0]
print(evens)

# Generator expression: produces values one at a time, on demand
gen = (n * n for n in numbers)
print(gen.__class__.__name__)
print(next(gen), next(gen))

# Pass a generator expression straight into a function
print(sum(n * n for n in range(1, 1_000_001)))

Output:

[1, 4, 9, 16, 25, 36]
[2, 4, 6]
generator
1 4
333333833333500000

Use a list comprehension when you need the full list, for example, to index it or loop over it several times. Use a generator expression when you only need to go through the values once, especially with large data, because it uses very little memory no matter how many items it produces.

Learn 45+ in-demand full-stack development skills and tools, including Frontend Development, Backend Development, Version Control and Collaboration, Database Management, and AI-Assisted Development, with our Full Stack Developer Course.

How Python Evaluates Expressions

Evaluating expressions in Python involves two separate sets of rules. Operator precedence determines which operations apply first. Evaluation order decides when Python computes each operand, and It computes operands from left to right.

The example below makes this visible. Multiplication is applied before addition, but the three function calls still run in the order they appear.

def show(n):
    print("evaluating", n)
    return n

# Operands are evaluated left to right, even though * is applied before +
result = show(1) + show(2) * show(3)
print("result:", result)

Output:

evaluating 1
evaluating 2
evaluating 3
result: 7

There are a few more rules to know:

  • In an assignment such as x = expression, the right-hand side is evaluated first, and then the result is stored.
  • and and or short-circuit, so their right-hand operand may not be evaluated at all.
  • In a conditional expression, only the chosen branch gets evaluated.
  • Parentheses always override precedence, so (a + b) * c adds before multiplying.

Operator Precedence in Python

Operator precedence decides which operator Python applies first when an expression contains more than one operator. Operators higher in this table bind more tightly than the ones below them. Operators in the same row have the same precedence.

Precedence

Operator

Description

Highest

(...), [...], {...}

Parentheses and literal displays

x[i], x[i:j], x(...), x.attr

Subscription, slicing, call, attribute reference

await x

Await expression

**

Exponentiation

+x, -x, ~x

Unary plus, unary minus, bitwise NOT

*, @, /, //, %

Multiplication, matrix multiplication, division, floor division, remainder

+, -

Addition, subtraction

<<, >>

Shifts

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

in, not in, is, is not, <, <=, >, >=, !=, ==

Comparisons, membership, identity

not x

Boolean NOT

and

Boolean AND

or

Boolean OR

if ... else

Conditional expression

lambda

Lambda expression

Lowest

:=

Assignment expression

print(2 + 3 * 4)        # * before +
print((2 + 3) * 4)      # parentheses first
print(10 - 4 / 2)       # / before -
print(2 * 3 ** 2)       # ** before *
print(5 > 3 and 2 > 4)  # comparisons before and
print(not 5 == 5)       # == before not
print(-2 ** 2)          # ** before unary minus

Output:

14
20
8.0
18
False
False
-4

The last line surprises many people: -2 ** 2 is -4, because ** binds more tightly than the unary minus on its left. Write (-2) ** 2 if you want 4. When an expression is hard to read, add parentheses even where they aren't required.

Operator Associativity in Python

Associativity decides the order in which operators of the same precedence are applied. Most Python operators are left-associative, so they're applied from left to right. The exponent operator ** is the exception: it's right-associative, so 2 ** 3 ** 2 means 2 ** (3 ** 2).

print(100 / 10 / 2)    # left to right: (100 / 10) / 2
print(20 - 5 - 3)      # left to right: (20 - 5) - 3
print(2 ** 3 ** 2)     # right to left: 2 ** (3 ** 2)
print((2 ** 3) ** 2)

Output:

5.0
12
512
64

Comparison operators don't associate in the usual way. As you saw earlier, a < b < c is treated as a chained comparison, a < b and b < c, rather than (a < b) < c.

Wondering how Software Engineers reach senior and leadership roles? Explore the skills, technologies, salary growth, and career progression behind one of the world's most in-demand jobs with this software engineer roadmap.

Common Mistakes With Python Expressions

These mistakes with expressions in Python trip up beginners and experienced developers coming from other languages:

print(2 ^ 3)       # XOR, not power
print(2 ** 3)      # power

print(-2 ** 2)     # -(2 ** 2)
print((-2) ** 2)

print(7 // 2)      # floor division rounds down...
print(-7 // 2)     # ...toward negative infinity, not toward zero

a = [1, 2]
b = [1, 2]
print(a == b, a is b)

Output:

1
8
-4
4
3
-4
True False
  • ^ is bitwise XOR in Python, not a power operator, so 2 ^ 3 gives 1. Use ** for exponents.
  • -2 ** 2 is -4, not 4, because the exponent is applied before the minus sign.
  • Floor division rounds down rather than toward zero, so -7 // 2 is -4.
  • Two lists with equal contents are usually different objects, so a is b can be False even when a == b is True. Use == for values and save is for None.

Key Takeaways

  • Expressions in Python are any code that produces a value, and statements are complete instructions that often contain expressions.
  • Python's core expression types are arithmetic, relational, logical, and bitwise, with identity and membership checks for objects and containers.
  • Conditional expressions, the walrus operator, lambdas, and comprehensions let you write compact, readable code for common patterns.
  • Operator precedence determines which operator applies first, while operands are evaluated left to right.
  • Most operators are left-associative, ** is right-associative, and comparisons chain, so use parentheses whenever the order isn't obvious.

Conclusion

Expressions in Python are at work in almost every line you write, from a simple sum to a one-line filter over thousands of records. Once you know the main types of expressions and the rules Python follows to evaluate them, you can predict exactly what your code will compute and avoid subtle bugs caused by precedence or short-circuiting.

Ready to go deeper? Dive into Python's core concepts, from basics to advanced techniques, and build real-world applications with Simplilearn's Python Certification course, which turns your skills into career opportunities through hands-on projects and industry-relevant experience.

To expand your expertise beyond Python, explore software development courses that help you master programming concepts, learn industry-relevant tools, and develop the skills needed to build real-world applications and advance your software development career.

FAQs

1. Is a function call an expression in Python?

Yes. A call such as len(items) or max(a, b) evaluates to the value the function returns so that you can use it anywhere an expression is allowed, including inside larger expressions like len(items) + 1. A function that has no return statement still produces a value: None.

2. What is the difference between a literal and an expression in Python?

A literal is a fixed value written directly in your code, such as 42, 3.14, "hello", True, or None. Every literal is an expression because it produces a value, but not every expression is a literal. x + 1 is an expression that Python computes while the program runs.

3. What does eval() do with an expression in Python?

eval() takes a string, parses it as a Python expression, and returns the result, so eval("2 + 3 * 4") returns 14. Avoid calling eval() on input from users or other untrusted sources, because it can run any Python code. For turning strings into Python literals safely, use ast.literal_eval().

4. Can a lambda expression contain more than one expression?

No. A lambda's body must be a single expression, and it can't contain statements such as assignments, loops, or return. You can still use a conditional expression inside it, as in lambda x: "even" if x % 2 == 0 else "odd". For anything more complex, use a regular function defined with def.

5. What is an expression statement in Python?

An expression statement is an expression on its own line whose value isn't stored or used. Calling a function such as print("Hello") or items.append(4) is the most common example. Python evaluates the expression, mainly for its side effects, and discards the result.

About the Author

Kusum SainiKusum Saini

Kusum Saini is the Director - Principal Architect at Simplilearn. She has over 12 years of IT experience, including 3.5 years in the US. She specializes in growth hacking and technical design and excels in n-layer web application development using PHP, Node.js, AngularJS, and AWS technologies.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.
  • *All trademarks are the property of their respective owners and their inclusion does not imply endorsement or affiliation.
  • Career Impact Results vary based on experience and numerous factors.