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:
| Parameter | Type | Description |
|---|---|---|
| operand1, operand2 | Number / Expression | Values being evaluated. |
| <operator> | Symbol / Keyword | Arithmetic, comparison, or boolean operator. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Python Variables and Data Types with Examples
Variables in Python are containers for storing data values. Python is dynamically typed, so you do not need to declare types explicitly.
Python If...Else Conditional Statements with Examples
Decision making in Python is performed using if, elif, and else statements to execute code blocks based on boolean conditions.
Python Type Casting and Conversion with Examples
Type casting is the process of converting a variable from one data type into another using Python built-in functions.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.