Python:Python Operators: Arithmetic, Comparison & Logical
Python•Operators

Python Operators: Arithmetic, Comparison & Logical

Python supports a comprehensive set of operators including arithmetic (+, -, *, /, //, %, **), comparison (==, !=, <, >), and logical operators (and, or, not).

Syntax

result = operand1 <operator> operand2

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
operand1, operand2Number / ExpressionValues being evaluated.
<operator>Symbol / KeywordArithmetic, comparison, or boolean operator.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Arithmetic & Comparison Operators in Python
a = 17
b = 5

print(f"Addition:       {a} + {b}  = {a + b}")
print(f"Division:       {a} / {b}  = {a / b:.2f}")
print(f"Floor Division: {a} // {b} = {a // b}")
print(f"Modulus:        {a} % {b}  = {a % b}")
print(f"Exponentiation: {b} ** 3   = {b ** 3}")

# Logical Operators
is_adult = True
has_ticket = False
can_enter = is_adult and has_ticket
print(f"Can Enter: {can_enter} (is_adult and has_ticket)")
Expected Output:
Addition:       17 + 5  = 22
Division:       17 / 5  = 3.40
Floor Division: 17 // 5 = 3
Modulus:        17 % 5  = 2
Exponentiation: 5 ** 3   = 125
Can Enter: False (is_adult and has_ticket)

How It Works: Step-by-Step

  • Lines 5-9: Performs division (/ returns float, // truncates to integer, % returns remainder).
  • Lines 12-15: Demonstrates logical AND which requires both operands to be True.

Key Concepts

  • Standard division / always returns a floating-point number in Python 3.
  • Floor division // rounds down to the nearest integer.
  • Python uses English keywords and, or, and not rather than &&, ||, and !.

Common Mistake: Confusing assignment = with comparison ==

= assigns a value to a variable, while == checks for equality.

❌ Incorrect
if x = 10: # SyntaxError: invalid syntax
    pass
✅ Correct
if x == 10:
    print("x equals 10")

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler