Python basics: features, data types and operators
Python basics: features, data types, literals, variables, type conversion, and all core operators (arithmetic, comparison, assignment, logical, bitwise, membership, identity) with precedence and examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use Python for quick calculations, data processing, automation scripts, and as a first language for learning programming concepts. A clear understanding of Python’s basic features, data types, and operators lets you write correct programs and avoid logical errors in later topics such as Decision control statements, Loops, Functions, and Object-oriented programming.
Key ideas
- Python: A high-level, general-purpose, interpreted language with readable, indentation-based syntax.
- Exact statement: “Python executes code line by line (interpreted), uses indentation to define blocks, supports multiple paradigms (procedural, object-oriented, functional), and has automatic memory management (garbage collection).”
- Assumptions: CPython interpreter unless stated otherwise; standard library available.
- Feature (of a language): A characteristic that affects how we write and run programs. Python’s key features used in first-year courses:
- High-level: Close to human language; abstracts machine details.
- Dynamically typed: Type of a variable is checked at runtime; no type declarations for variables.
- Interpreted/interactive: Code can be run line-by-line in a REPL (Read–Eval–Print Loop).
- Cross-platform: Same code can run on multiple operating systems.
- Large standard library: Many ready modules for I/O, math, files, etc.
- Indentation-based blocks: Indentation defines blocks (suites) for if, for, while, functions, classes.
- Identifier: The name you give to variables, functions, classes. Rules: use letters, digits, underscore; cannot start with a digit; case-sensitive; keywords are not allowed as identifiers.
- Literal: A fixed value written directly in code (e.g., 10, 3.14, 'Hi').
- Variable: A named reference to an object (value) in memory. In Python, the name points to an object; the object has a type.
- Object: A piece of data with a type and possibly methods. Everything in Python is an object.
- Expression: A combination of values, variables, and operators that evaluates to a single value.
- Statement: A complete instruction (e.g., assignment, import, print call).
- Data type: A classification of data that defines allowed values and operations.
Built-in data types commonly examined:
- int: Integers of arbitrary size. Examples: 0, -5, 123456.
- float: Real numbers in double precision (implementation-dependent, typically IEEE 754 binary64). Examples: 0.0, -2.5, 1.0e3.
- complex: Complex numbers of the form a + bj where a, b are floats; j is the imaginary unit. Example: 3+4j.
- bool: Logical True or False (subclass of int; True behaves like 1, False like 0 in arithmetic).
- str: Immutable sequence of Unicode characters. Example: "Hello".
- bytes: Immutable sequence of bytes (0–255). Example: b"ABC".
- bytearray: Mutable sequence of bytes.
- range: Arithmetic progression of integers, used in loops.
- NoneType: The type of the single value None, representing “no value”.
- list, tuple, set, dict: Covered fully in Lists and tuples and Sets and dictionaries topics; know they are containers to hold multiple values.
Properties to remember:
- Mutability: Whether an object can change after creation.
- Immutable: int, float, bool, complex, str, bytes, tuple, range.
- Mutable: list, dict, set, bytearray.
- Dynamic typing: The type is attached to the object, not the variable name. A name can be rebound to any type.
- Type conversion (casting): Creating a new object of a target type from a value, using constructors like int(x), float(x), str(x), bool(x), complex(x), bytes(x), list(x), tuple(x), set(x).
- Exact statement: “Explicit conversion creates a new object; it does not modify the original (especially for immutable types).”
Operators and evaluation:
- Operator: A symbol that performs an operation on operands.
- Operand: The value(s) the operator acts on.
- Precedence: The rule that determines which operator is evaluated first in an expression.
- Associativity: The rule that determines evaluation order when operators have the same precedence (e.g., left-to-right or right-to-left).
Operator categories you must know:
- Arithmetic: +, -, *, / (true division), // (floor division), % (modulus), ** (exponentiation).
- True division / returns float even for integers (e.g., 5/2 = 2.5).
- Floor division // returns the mathematical floor of the exact quotient. For positive a, b: a//b equals integer part. For negatives, it rounds down to the more negative integer (e.g., -3//2 == -2).
- Modulus % gives the remainder with the sign of the divisor (e.g., -3 % 2 == 1 because (-2)*2 + 1 = -3).
- Comparison (relational): ==, !=, <, >, <=, >=. Returns bool. Comparisons can be chained: a < b < c is equivalent to (a < b) and (b < c) without evaluating b twice.
- Assignment: =, with augmented forms like +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=.
- Logical: and, or, not. Short-circuiting: and stops on first False-like value; or stops on first True-like value; not flips truth value. and and or return one of the operands (the last evaluated), not necessarily a bool.
- Bitwise (on integers): ~ (bitwise NOT), & (AND), | (OR), ^ (XOR), << (left shift), >> (right shift).
- Membership: in, not in (e.g., 'a' in 'cat' is True).
- Identity: is, is not (tests whether two names refer to the same object in memory). Do not confuse with equality (==), which tests value equality.
Truthiness rules:
- Falsy: False, None, 0, 0.0, 0j, empty sequences/collections ("", [], (), {}, set(), range(0)).
- Truthy: Everything else.
Exact statements commonly asked:
- “Operator precedence from highest to lowest (core subset for exams): **, unary + -, ~, *, /, //, %, +, -, <<, >>, &, ^, |, comparison operators, not, and, or, assignment.”
- “Exponentiation ** is right-associative; most binary arithmetic operators are left-associative.”
- “In Python, names are references to objects; assignment binds a name to an object.”
What to draw if asked for a diagram (no image, describe drawing):
- Draw three labeled boxes for variable names: a, b, c. Draw separate rounded rectangles for objects: an integer object 10, another integer object 10, and a list object [1,2]. Draw arrows from a and b to the same integer 10 object (to show multiple names can refer to the same immutable value after assignment like a=b=10). Draw an arrow from c to the list [1,2]. Then show c.append(3) and redraw the same list object now as [1,2,3] with the arrow from c unchanged, to illustrate mutability.
Formulas
For this programming topic, learn the syntax patterns instead:
a = b— Assignment: binds name a to the value of b.x, y = y, x— Multiple assignment and swapping.name: type_hint = value— Optional type hint syntax (not enforced at runtime).int(x), float(x), str(x), bool(x), complex(a, b)— Type conversion constructors.a + b, a - b, a * b, a / b, a // b, a % b, a ** b— Arithmetic operators.a == b, a != b, a < b, a <= b, a > b, a >= b— Comparison operators.a and b, a or b, not a— Logical operators (short-circuit evaluation).a & b, a | b, a ^ b, ~a, a << n, a >> n— Bitwise integer operators.x in s, x not in s— Membership tests for sequences/collections.a is b, a is not b— Identity tests (same object in memory).input(prompt)— Read a line as str from standard input.print(values, sep=' ', end='\n')— Print values to standard output.type(x), isinstance(x, T)— Inspect the type.- Operator associativity to remember:
a ** b ** cevaluates asa ** (b ** c)(right-associative);a - b - cevaluates as(a - b) - c(left-associative).
Worked examples
Example 1: Arithmetic operators and types Complete Python program:
# Read two integers and show arithmetic results and their types
a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))
print(f"a + b = {a + b}")
print(f"a - b = {a - b}")
print(f"a * b = {a * b}")
print(f"a / b = {a / b}") # true division -> float
print(f"a // b = {a // b}") # floor division -> int
print(f"a % b = {a % b}") # modulus -> int
print(f"a ** b = {a ** b}") # exponentiation
print(f"type(a / b) = {type(a / b)}")
print(f"type(a // b) = {type(a // b)}")
Sample input:
7
3
Exact output:
a + b = 10
a - b = 4
a * b = 21
a / b = 2.3333333333333335
a // b = 2
a % b = 1
a ** b = 343
type(a / b) = <class 'float'>
type(a // b) = <class 'int'>
Example 2: Operator precedence and associativity Complete Python program:
# Demonstrate precedence: ** then *,/,//,% then +,- then shifts and bitwise then comparisons then logical
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))
expr = x + y * z ** 2 // 5 % 7
# Explanation (not printed): z ** 2 first; then y * (z**2); then // 5; then % 7; then + x
print(f"Expression value = {expr}")
# Associativity demo
left = x - y - z # (x - y) - z
right = x ** y ** z # x ** (y ** z)
print(f"left-associative subtraction = {left}")
print(f"right-associative exponentiation = {right}")
Sample input:
2
3
4
Exact output:
Expression value = 4
left-associative subtraction = -5
right-associative exponentiation = 2417851639229258349412352
Explanation for the expression when x=2, y=3, z=4:
- z ** 2 = 16
- y * 16 = 48
- 48 // 5 = 9 (floor of 9.6)
- 9 % 7 = 2
- x + 2 = 4 Since *, //, and % have the same precedence and are left-associative, the exact value is 4.
Example 3: Bitwise operators with integer masks Complete Python program:
n = int(input("Enter n: ")) # e.g., 29
m = int(input("Enter mask: ")) # e.g., 15
print(f"n = {n} bin: {bin(n)}")
print(f"m = {m} bin: {bin(m)}")
print(f"n & m = {n & m} bin: {bin(n & m)}")
print(f"n | m = {n | m} bin: {bin(n | m)}")
print(f"n ^ m = {n ^ m} bin: {bin(n ^ m)}")
print(f"~n = {~n} bin: {bin(~n)}")
print(f"n << 2 = {n << 2} bin: {bin(n << 2)}")
print(f"n >> 2 = {n >> 2} bin: {bin(n >> 2)}")
Sample input:
29
15
Exact output:
n = 29 bin: 0b11101
m = 15 bin: 0b1111
n & m = 13 bin: 0b1101
n | m = 31 bin: 0b11111
n ^ m = 18 bin: 0b10010
~n = -30 bin: -0b11110
n << 2 = 116 bin: 0b1110100
n >> 2 = 7 bin: 0b111
Common mistakes
- Forgetting short-circuit behavior: expecting both sides of
andororto always evaluate. - Misunderstanding floor division with negatives: believing
-3 // 2 == -1(it is -2 in Python). - Assuming
/returns int for integers (it returns float). Use//for integer-like quotient. - Losing data in type conversion: using
int(2.9)and expecting rounding (it truncates toward zero -> 2). - Mixing strings and numbers without conversion:
"5" + 2raises TypeError; must useint("5") + 2. - Assuming bools are separate from ints in arithmetic:
True + True == 2in Python. - Relying on exact decimal representation of floats:
0.1 + 0.2is not exactly 0.3 due to binary floating-point. - Misreading operator precedence: evaluating
a + b * cas(a + b) * c. - Using mutable default arguments in functions (covered later in Functions topic); know mutability basics here.
For your exam
- Short notes: Python features (interpreted, dynamic typing, indentation), built-in numeric types (int, float, complex), truthiness rules, membership vs identity, bitwise operators use-cases. Include 3–4 crisp points and one code line demonstrating each.
- Programs: simple arithmetic calculator with two inputs; evaluate an expression showing precedence; bitwise mask operations; show type conversion of inputs (str to int/float) and error handling message. Provide complete code, sample input, and exact output.
- Diagram question: name binding and mutability diagram as described above; label names, objects, arrows; explain in 3–4 sentences.
- Operator precedence: list from highest to lowest (at least the main categories) and state associativity of **; give a worked example.
- Traps: floor division and modulus with negatives, float imprecision; explain with one line of REPL output each. For full marks, write precise definitions in bold terms, correct syntax, correct precedence order, minimal but accurate code, and clean, labeled diagrams (when asked). Avoid vague statements; show at least one example per definition.
Quick check
- What is the difference between
==andisin Python? - Evaluate in Python:
-7 // 3and-7 % 3. - Which operator has higher precedence:
**or*? What is the associativity of**? Answers: 1)==tests value equality;istests identity (same object). 2)-7 // 3is -3;-7 % 3is 2. 3)**has higher precedence; it is right-associative.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?