Unit 1: Python basics

ECAP776 8 min read

I. Orientation — The Python Programming Model

Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes readable syntax, automatic memory management, and rapid development. A Python program consists of statements and expressions executed by an interpreter, normally from top to bottom.

  • Core characteristics:
    • Readable syntax: Indentation marks code blocks instead of braces.
    • Interpreted execution: The Python interpreter executes source code without a separate manual compilation stage.
    • Dynamic typing: A variable name can refer to objects of different types at different times.
    • Strong typing: Python does not silently combine incompatible values such as "5" + 2.
    • Object-based model: Values—including integers, strings, functions, and classes—are objects.
    • Portability: The same source program can generally run on Linux, Windows, and macOS when its dependencies are available.
    • Extensibility: The standard library and third-party packages support web development, automation, data science, artificial intelligence, and other fields.

A. Introduction

Python provides a concise way to express algorithms by combining values, variables, statements, and reusable functions.

  • Program structure: A simple program may receive input, process it, and produce output.
    • input() reads text from the user.
    • Assignment stores an object reference under a name.
    • print() displays a textual representation of a value.
  • Identifiers: Names may contain letters, digits, and underscores, but cannot begin with a digit.
    • Valid examples include total, student_2, and _temporary.
    • Python identifiers are case-sensitive, so score and Score are different.
    • Reserved keywords such as if, for, def, and return cannot be identifiers.
  • Assignment: The statement radius = 4 binds the name radius to the integer object 4; it does not declare a fixed variable type.
  • Comments: Text following # is ignored by the interpreter and should clarify purpose rather than restate obvious code.
  • Indentation: Consistent indentation is syntactically required. Four spaces per level is the standard convention.
  • Basic input-processing-output example:
PYTHON
name = input("Name: ")
age = int(input("Age: "))
next_age = age + 1
print(name, "will be", next_age, "next year.")
  • Concrete interpretation:
    • name stores the text returned by the first input().
    • age stores an integer produced by converting input text with int().
    • next_age is the value of age + 1.
    • If the inputs are Mina and 19, the output is Mina will be 20 next year.

II. Values and Expressions — Representing and Processing Data

Values are the information manipulated by a program, while operators form expressions that calculate, compare, or combine those values.

A. Data types and operators

A data type determines a value’s representation, valid operations, and general behavior.

  • Numeric types:
    • int: Represents whole numbers of arbitrary practical size, such as -7, 0, and 125.
    • float: Represents floating-point numbers, such as 3.14; binary representation means values such as 0.1 may not be stored exactly.
    • complex: Represents numbers with real and imaginary parts, such as 2 + 3j.
    • bool: Contains True and False; it is used primarily in conditions.
  • Text and collection types:
    • str: An immutable sequence of Unicode characters, such as "Python".
    • list: A mutable ordered collection, such as [10, 20, 30].
    • tuple: An immutable ordered collection, such as (10, 20).
    • range: An arithmetic sequence commonly used in loops, such as range(1, 5).
    • dict: A mutable mapping of keys to values, such as {"name": "Asha", "age": 20}.
    • set: An unordered collection of unique hashable elements, such as {2, 4, 6}.
    • NoneType: Has the single value None, which commonly denotes the absence of a value.
  • Type inspection and conversion:
    • type(value) returns the type of value.
    • int("12"), float("2.5"), and str(40) explicitly convert compatible values.
    • Invalid conversion, such as int("twelve"), raises ValueError.
  • Arithmetic operators:
    • +, -, and * perform addition, subtraction, and multiplication.
    • / performs true division: 7 / 2 produces 3.5.
    • // performs floor division: 7 // 2 produces 3.
    • % gives the remainder: 7 % 2 produces 1.
    • ** performs exponentiation: 2 ** 3 produces 8.
  • Comparison operators: ==, !=, <, <=, >, and >= produce Boolean results. Equality uses ==; assignment uses =.
  • Logical operators:
    • and is true when both operands are truthy.
    • or is true when at least one operand is truthy.
    • not reverses truth value.
    • Values such as 0, None, "", and empty collections are falsy; many other values are truthy.
  • Sequence operators:
    • + concatenates compatible sequences: "Py" + "thon" gives "Python".
    • * repeats a sequence: "ha" * 3 gives "hahaha".
    • in and not in test membership: 2 in [1, 2, 3] is True.
  • Identity operators: is and is not test whether operands refer to the same object, not merely equal values. Use value is None for a None check, but use a == b for ordinary value equality.
  • Assignment operators: x += 3 is an augmented assignment corresponding broadly to x = x + 3.
  • Precedence: Parentheses are evaluated first, followed broadly by exponentiation, unary operations, multiplication-level operations, addition-level operations, comparisons, not, and, and or. Parentheses should make nontrivial intent explicit.
  • Worked example:
PYTHON
price = 80.0
quantity = 3
discount = 0.10
subtotal = price * quantity
total = subtotal * (1 - discount)
eligible = quantity >= 3 and total > 200
print(total, eligible)
  • Result analysis:
    • price, quantity, and discount denote unit price, item count, and discount rate.
    • subtotal is 80.0 × 3 = 240.0.
    • total is 240.0 × (1 − 0.10) = 216.0.
    • eligible becomes True because both comparisons are true.

B. Applications and limitations

Selecting suitable types and operators improves correctness, clarity, and efficiency.

  • Mutability: List elements can be changed, but string and tuple elements cannot be replaced in place.
  • Aliasing: After b = a, both names may refer to the same mutable list; changing it through b is then visible through a.
  • Floating-point limitation: Financial or exact decimal calculations may require decimal.Decimal rather than binary float.
  • Runtime errors: Division by zero raises ZeroDivisionError, and incompatible operations can raise TypeError.

III. Program Flow — Selecting and Repeating Actions

Control flow determines which statements execute, how often they execute, and when execution leaves a block.

A. Control statements

Control statements implement decisions, iteration, and explicit changes in normal execution order.

  • Conditional execution: An if statement executes its block when its condition is truthy. Optional elif branches test further conditions, while else handles the remaining case.
  • Condition ordering: Branches are tested from top to bottom, and only the first matching if/elif branch executes.
  • while loop: Repeats while a condition remains truthy; its body must normally change some state so that termination becomes possible.
  • for loop: Iterates directly over an iterable such as a string, list, dictionary, or range.
    • range(start, stop, step) includes start but excludes stop.
    • Thus, range(1, 5) produces 1, 2, 3, 4.
  • Loop-control statements:
    • break immediately exits the nearest enclosing loop.
    • continue skips the remainder of the current iteration.
    • pass performs no action and serves as a syntactic placeholder.
  • Nested control structures: A loop may contain a conditional or another loop; indentation identifies each block.
  • Worked example:
PYTHON
total = 0

for number in range(1, 6):
    if number == 4:
        continue
    total += number

print(total)
  • Execution trace:
    • number successively receives 1, 2, 3, 4, and 5.
    • When number == 4, continue prevents addition.
    • total becomes 1 + 2 + 3 + 5 = 11.
  • Loop safety: An unintended infinite loop occurs when a while condition never becomes false; for example, forgetting to update its counter.
  • Loop else clause: An else attached to a loop runs after normal completion but not when the loop ends through break.

IV. Functional Decomposition — Building Reusable Operations

A function is a named, reusable block of code that can receive arguments, perform a task, and optionally return a result.

A. Functions

Functions divide programs into manageable units while reducing duplication and clarifying intent.

  • Definition syntax: def introduces a function, followed by its name, parameter list, colon, and indented body.
  • Parameters and arguments:
    • A parameter is a name in a function definition.
    • An argument is a value supplied during a function call.
    • Arguments may be positional, such as power(2, 3), or keyword-based, such as power(base=2, exponent=3).
  • Return value: return immediately ends the call and sends a value to the caller. A function reaching its end without return returns None.
  • Default parameters: A definition such as def greet(name, message="Hello") uses "Hello" when the second argument is omitted.
  • Scope:
    • Names assigned inside a function are normally local to that call.
    • Names defined outside functions belong to an enclosing or global scope.
    • Local variables should generally be preferred over modifying global state.
  • Documentation: A docstring is a string placed first in the function body and explains the function’s purpose, parameters, and result.
  • Worked example:
PYTHON
def rectangle_area(width, height=1):
    """Return the area of a rectangle."""
    if width < 0 or height < 0:
        raise ValueError("Dimensions must be non-negative")
    return width * height

area = rectangle_area(5, height=3)
print(area)
  • Call analysis:
    • width and height are parameters representing rectangle dimensions.
    • The call supplies 5 positionally and 3 through the keyword height.
    • The condition enforces the function’s non-negative-input requirement.
    • The returned area is 5 × 3 = 15.
  • Function design: A focused function should perform one coherent task, use descriptive names, validate essential preconditions, and return data rather than printing when the caller may need the result.
  • Built-in and imported functions:
    • Built-ins such as len(), sum(), and round() are immediately available.
    • Module functions are accessed after importing, as in math.sqrt(25).
  • Recursion: A recursive function calls itself and requires a base case that stops further calls; without one, Python eventually raises RecursionError.