Expression in Python

 

What is an Expression in Python?

An expression in Python is a combination of values, variables, and operators that produces a value when evaluated.

Example:

x = 10 + 5

Operator Precedence in Python

Python follows the PEMDAS rule to evaluate expressions:

  • P: Parentheses
  • E: Exponentiation
  • MD: Multiplication and Division (left to right)
  • AS: Addition and Subtraction (left to right)

Python Expression Examples

Evaluate the following expressions:


print(10 + 5 * 2)  # Output: 20
print((10 + 5) * 2)  # Output: 30
print(10 / 3)  # Output: 3.3333
print(10 // 3)  # Output: 3
print(2 ** 4)  # Output: 16
print(15 % 4)  # Output: 3
print(5 + 3 * 2 - 1)  # Output: 10
print((8 - 3) * 2)  # Output: 10
print(18 / 4)  # Output: 4.5
print(18 // 4)  # Output: 4
        

Mathematical Representation

Python expressions can be represented mathematically. Consider the expression:

\[ 10 + 5 \times 2 \]

Since multiplication has higher precedence than addition, the expression evaluates as:

\[ 10 + (5 \times 2) = 10 + 10 = 20 \]


PDF

Expressions in Python

Summary

  • Python expressions evaluate to a value.
  • Operators follow precedence rules.
  • Expressions can be mathematical or string-based.

 

©Postnetwork-All rights reserved.