Unit 1: Basics of Python

CAP776 — Programming In Python 9 min read

I. Orientation — Python’s Core 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. Python programs are executed by an interpreter, allowing learners to run instructions interactively or from saved files.

  • Readable syntax: Indentation defines blocks, while braces and semicolons are generally unnecessary.
  • Interpreted execution: The Python interpreter executes source code without requiring a separate manual compilation step.
  • Dynamic typing: A variable receives its type from the assigned value; for example, x = 10 makes x an integer.
  • Object-based data model: Values such as integers, strings, lists, and functions are objects with types and associated operations.
  • Case sensitivity: total, Total, and TOTAL are three different identifiers.
  • Indentation convention: Four spaces per indentation level is the standard convention.
  • Comments: A # begins a single-line comment.
  • Common workflow:
    1. Write instructions as Python source code.
    2. Execute them through an interpreter.
    3. Observe output or errors.
    4. Edit and rerun the code.
PYTHON
# A basic Python program
message = "Hello, Python!"
print(message)

Here, message is a variable referring to a string, and print() displays that string.

II. Python Development Environments — Writing and Running Code

A. Introduction to Python IDLE, Jupyter Notebook, Google Colab

A Python development environment provides tools for entering, executing, testing, and organizing Python code.

  1. Python IDLE

    • Meaning: IDLE is Python’s Integrated Development and Learning Environment and is commonly installed with standard Python distributions.
    • Interactive Shell: The >>> prompt accepts one instruction at a time and immediately displays its result.
    • Editor window: A separate editor supports complete programs saved with the .py extension.
    • Execution: In the editor, Run → Run Module or F5 executes the current file.
    • Best use: IDLE is suitable for learning syntax, testing short statements, and creating small scripts.
  2. Jupyter Notebook

    • Notebook structure: A notebook consists of cells, usually either Code cells or Markdown cells.
    • Cell execution: Shift+Enter executes a selected code cell and moves to the next cell.
    • Persistent state: Variables remain available while the notebook kernel is running, although cells can be executed in a non-linear order.
    • File format: Notebooks are normally stored as .ipynb files.
    • Best use: Jupyter is effective for data analysis, demonstrations, calculations, and explanations combining code with formatted text.
  3. Google Colab

    • Cloud platform: Colab runs Jupyter-style notebooks through a web browser using Google-hosted computing resources.
    • Storage: Notebooks can be stored in Google Drive or downloaded as .ipynb or .py files.
    • Collaboration: Sharing and simultaneous editing resemble other Google Workspace tools.
    • Runtime behavior: Variables and uploaded temporary files may disappear when the hosted runtime resets.
    • Best use: Colab allows Python programming without a local installation and can provide optional GPU or TPU runtimes.
PYTHON
language = "Python"
language

In a notebook, the final expression may be displayed automatically; in a .py file, print(language) is required to produce visible output.

III. Program Workflow — From Source Code to Execution

A. Creating, saving, and executing a Python file

A Python file is a plain-text source file containing instructions that the Python interpreter can execute.

  • Creation: Open IDLE, a text editor, or an integrated development environment and enter valid Python statements.
  • Saving: Use a meaningful filename ending in .py, such as area.py; avoid naming a file after standard modules such as math.py.
  • Execution in IDLE: Save the file and press F5 or select Run Module.
  • Execution in a terminal: Navigate to the file’s directory and issue an appropriate command.
TEXT
python area.py

On some systems, the command is python3 area.py.

  • Program entry: Python processes top-level statements from first to last.
  • Syntax errors: Invalid grammar, such as a missing closing parenthesis, prevents normal execution.
  • Runtime errors: An instruction may be syntactically valid but fail during execution, as in 10 / 0.
  • Logical errors: A program runs but produces an incorrect result because its algorithm or formula is wrong.
  • Worked example: A saved file can calculate a rectangle’s area.
PYTHON
length = 8
width = 5
area = length * width
print("Area:", area)

Here, length and width represent side lengths, and area stores their product, 40.

IV. Data and Expressions — Interaction and Calculation

A. User input/output operations

Input supplies data to a program, while output communicates processed information to the user.

  • Standard input: input(prompt) displays an optional prompt and returns the entered text as a string.
  • Type conversion: Numeric input must normally be converted using int() or float().
  • Standard output: print() displays values separated by spaces and ends with a newline by default.
  • Formatting: An f-string embeds expressions inside braces prefixed by f.
  • Optional arguments:
    • sep changes the separator between printed values.
    • end changes the characters printed at the end.
PYTHON
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"{name} will be {age + 1} next year.")

Here, name remains text, age is converted to an integer, and {age + 1} is evaluated before display.

B. Numeric data types

Python’s principal built-in numeric types represent whole numbers, approximate real numbers, and complex numbers.

  • int: Represents integers of arbitrary precision, such as -12, 0, or 4500.
  • float: Represents floating-point values, such as 3.14 or -0.5; binary representation can cause approximations such as 0.1 + 0.2.
  • complex: Represents numbers of the form (a+bj), where a is the real part, b is the imaginary coefficient, and j denotes the imaginary unit.
  • Boolean relationship: bool is a subclass of int; True behaves numerically like 1, and False like 0.
  • Inspection: type(value) reports a value’s type.
  • Conversion: int(4.8) gives 4, while float(6) gives 6.0; integer conversion truncates rather than rounds.
PYTHON
count = 25          # int
temperature = 36.5  # float
impedance = 3 + 4j  # complex

print(type(count))
print(impedance.real, impedance.imag)

The real and imaginary components of impedance are 3.0 and 4.0.

C. Operators

Operators combine or compare operands to form expressions and produce new values.

  • 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 >= return True or False.
  • Logical operators: and, or, and not combine or reverse Boolean conditions.
  • Assignment operators: =, +=, -=, *=, and similar forms update variables; x += 2 means x = x + 2.
  • Membership operators: in and not in test membership, as in "P" in "Python".
  • Identity operators: is and is not test whether references point to the same object; they should not replace == for ordinary value comparison.
  • Precedence: Parentheses are evaluated first, followed broadly by exponentiation, unary operations, multiplication-level operations, addition-level operations, comparisons, not, and, and or.
PYTHON
result = (5 + 3) * 2 ** 2
print(result)  # 32

Parentheses produce 8, exponentiation produces 4, and multiplication gives 32.

V. Control Flow — Decisions and Repetition

A. Conditional statements

Conditional statements select a block of code according to whether a Boolean expression is true or false.

  • if branch: Executes when its condition is true.
  • elif branch: Tests another condition only when preceding conditions were false.
  • else branch: Executes when no preceding condition was true.
  • Block structure: A colon introduces each branch, and consistently indented statements belong to that branch.
  • Truth values: Zero, empty strings, and empty containers are false-like; nonzero numbers and nonempty values are generally true-like.
  • Mutual exclusivity: In an ifelifelse chain, only the first matching branch executes.
PYTHON
score = 72

if score >= 75:
    grade = "Distinction"
elif score >= 50:
    grade = "Pass"
else:
    grade = "Fail"

print(grade)

Because 72 >= 75 is false but 72 >= 50 is true, the program assigns "Pass".

B. Python loops

Loops repeatedly execute a block, either for each item in an iterable or while a condition remains true.

  1. for loop

    • Principle: Iterates over elements of a sequence or another iterable.
    • Range generation: range(start, stop, step) generates integers from start up to, but not including, stop.
    • Concrete case: range(1, 4) produces 1, 2, and 3.
  2. while loop

    • Principle: Repeats while its condition evaluates to true.
    • Termination: The loop must normally change a value involved in its condition to avoid infinite repetition.
  • Loop controls:
    • break terminates the nearest loop immediately.
    • continue skips the remainder of the current iteration.
    • pass performs no action and serves as a placeholder.
  • Nested loops: A loop may occur inside another loop; the inner loop completes its iterations for each outer iteration.
PYTHON
total = 0

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

print(total)  # 15

The variable number takes values 1 through 5, and total accumulates their sum.

VI. Modular Programming — Reusable Operations

A. User-defined functions

A user-defined function is a named, reusable block of code created with def to perform a specific operation.

  • Definition syntax: A function header contains def, the function name, parentheses, and a colon; its body is indented.
  • Parameters: Names listed in the definition receive values supplied by the caller.
  • Arguments: Actual values passed during a call are arguments.
  • Return value: return ends the function and sends a result to the caller; without it, the function returns None.
  • Local scope: Variables assigned inside a function are normally local and unavailable outside it.
  • Default parameters: A declaration such as power=2 supplies a value when the caller omits that argument.
  • Keyword arguments: A call such as calculate(width=4, length=6) associates values explicitly with parameter names.
  • Documentation: A docstring placed immediately inside the function describes its purpose.
PYTHON
def rectangle_area(length, width=1):
    """Return the area of a rectangle."""
    return length * width

area = rectangle_area(6, 4)
print(area)  # 24

Here, length and width are parameters, 6 and 4 are arguments, and the returned product is assigned to area.

  • Design value: Functions reduce repetition, divide programs into manageable units, and make individual operations easier to test.
  • Naming convention: Descriptive lowercase names with underscores, such as calculate_total, improve readability.
  • Limitation: A function should have a clear responsibility; excessive dependence on global variables makes behavior harder to understand and maintain.