Unit 1: Python Environment Setup and Basics

CSR101 — Python Programming 4 min read

I. Orientation

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, a large standard library, and an interactive development style.

  • Execution model: A Python interpreter executes source code, usually stored in .py files or entered interactively.
  • Core convention: Indentation defines code blocks; consistent whitespace is therefore syntactically significant.
  • Dynamic typing: Variables refer to objects, and an object’s type is determined at runtime.
  • Object model: Values such as integers, strings, functions, and modules are Python objects.
  • Standard library: Built-in modules provide reusable tools for mathematics, files, dates, networking, and other tasks.
  • Current version: New development should use Python 3 because Python 2 reached end-of-life in 2020.

II. Development Environment — Installation and Execution

A. Installing Python and IDEs (Anaconda, Jupyter, VS Code)

A Python environment combines an interpreter with tools for writing, running, and managing programs.

  • Python installation: Download Python 3 from the official Python website; on Windows, select Add Python to PATH so python works in a terminal.
  • Verification: Check the installed interpreter and package manager with python --version and pip --version.
  • Anaconda: A distribution containing Python, scientific libraries, Jupyter, and the conda environment manager; it is useful for data science.
  • Jupyter: A notebook interface in which code, output, text, and visualizations are arranged in executable cells.
  • VS Code: A source-code editor that supports Python through the Python extension, interpreter selection, debugging, and terminal integration.
  • Environment isolation: A virtual environment prevents project dependencies from conflicting:
BASH
python -m venv .venv

B. Using Python shell as a calculator and running simple scripts

Python can execute individual expressions interactively or run a complete saved program.

  • Interactive shell: Entering 7 * 6 at the >>> prompt immediately returns 42, making the shell useful for experimentation.
  • Script file: A file such as hello.py stores reusable instructions:
PYTHON
price = 25
quantity = 4
print(price * quantity)
  • Execution: Run the file from its directory with python hello.py; the program prints 100.
  • Notebook distinction: Jupyter runs cells independently, while a script normally runs from top to bottom as one program.

III. Core Language Foundations — Syntax, Names, and Values

A. Python syntax

Python syntax is the set of rules governing how valid Python programs are written.

  • Statements: total = 10 + 5 performs an assignment; a newline generally ends the statement.
  • Indentation: A colon introduces an indented suite after constructs such as if, for, and def.
  • Case sensitivity: score, Score, and SCORE are three different names.
  • Comments: Text after # is ignored by the interpreter and should explain purpose rather than restate code.
  • Line continuation: Expressions inside parentheses can span lines without a backslash.

B. Variables

A variable is a name bound to an object rather than a fixed, predeclared storage type.

  • Assignment: age = 20 binds the name age to the integer object 20.
  • Reassignment: age = "twenty" is valid because names are dynamically typed.
  • Naming rules: Names may contain letters, digits, and underscores but cannot begin with a digit or use a keyword such as if.
  • Convention: Use descriptive snake_case names, such as student_count, rather than unclear names such as x1.

C. Data types

A data type determines a value’s representation and the operations it supports.

  • Numeric types: int represents arbitrary-precision integers, float represents floating-point values, and complex represents numbers such as 2 + 3j.
  • Logical type: bool has the values True and False.
  • Sequence types: str, list, and tuple store ordered items.
  • Other types: dict stores key-value pairs, set stores unique elements, and NoneType has the single value None.
  • Inspection: type(3.5) returns <class 'float'>.

D. Operators

Operators are symbols or keywords that perform operations on operands.

  • Arithmetic: +, -, *, /, //, %, and ** perform addition, subtraction, multiplication, division, floor division, remainder, and exponentiation.
  • Assignment: x += 2 is a compact form of x = x + 2.
  • Comparison: Operators such as < and == produce Boolean results.
  • Context dependence: 3 + 4 gives 7, whereas "3" + "4" gives "34" through string concatenation.

E. Expressions

An expression combines values, names, operators, or function calls and evaluates to a value.

  • Components: In price * quantity, the variables are operands and * is the operator.
  • Evaluation: If price = 12.5 and quantity = 4, the expression evaluates to 50.0.
  • Statement distinction: 2 + 3 is an expression; result = 2 + 3 is an assignment statement containing that expression.
  • Composition: Function calls can be nested, as in round(abs(-3.7)), which evaluates to 4.

F. Input/output

Input/output allows a program to receive data and communicate results.

  • Keyboard input: input("Name: ") displays a prompt and always returns a string.
  • Conversion requirement: Numeric input commonly requires conversion, as in age = int(input("Age: ")).
  • Screen output: print() displays one or more values; print("Total:", 25) inserts a space by default.
  • Control arguments: sep changes the separator and end changes the ending, for example print("A", "B", sep="-").

IV. Reusable Libraries — Modules and Mathematics

A. Module basics

A module is a Python file containing reusable definitions, statements, classes, or functions.

  • Importing: import random loads the module and permits qualified access such as random.randint(1, 6).
  • Selective import: from math import sqrt allows the direct call sqrt(25).
  • Aliases: import statistics as stats creates a shorter module name.
  • Namespace benefit: Qualified names such as math.pi show where an object originated and reduce naming conflicts.
  • Script entry point: if __name__ == "__main__": separates directly executed behavior from imported definitions.

B. Math module

The standard math module supplies constants and functions for real-number mathematics.

  • Constants: math.pi represents π and math.e represents Euler’s number.
  • Functions: math.sqrt(81), math.ceil(2.1), and math.floor(2.9) return 9.0, 3, and 2.
  • Angles: Trigonometric functions use radians; math.radians(180) converts 180 degrees to π radians.
  • Limitation: math.sqrt(-1) raises an error; complex-number operations require the cmath module.

V. Representing and Organizing Data — Text, Lists, and Conversion

A. Representing text

Python represents text as Unicode strings, enabling characters from many writing systems.

  • Literals: Text can be enclosed in single quotes, double quotes, or triple quotes: 'Python', "Python", or """Python""".
  • Unicode: A string such as "café" stores characters rather than raw display bytes.
  • Escapes: \n represents a newline, \t a tab, and \\ a literal backslash.
  • Raw strings: r"C:\new\test" treats backslashes literally, which is useful for path-like text.

B. String basics

A string is an immutable ordered sequence of Unicode characters.

  • Indexing: For word = "Python", word[0] is "P" and word[-1] is "n".
  • Slicing: word[1:4] produces "yth"; the ending index is excluded.
  • Immutability: word[0] = "J" is invalid; a new string must be constructed.
  • Operations: len(word) returns 6, "Py" in word returns True, and word.lower() returns "python".

C. List

A list is a mutable ordered collection whose elements may have different types.

  • Creation: items = ["pen", 3, True] creates a three-element list.
  • Access: items[0] returns "pen"; slicing follows the same rules as strings.
  • Mutation: append(), insert(), remove(), and pop() modify a list.
  • Aliasing: After b = items, both names refer to the same list; b = items.copy() creates a shallow copy.
  • Iteration: for item in items: processes each element in order.

D. Common data types summary

Python’s common types differ in purpose, ordering, and mutability.

  • Immutable scalars: int, float, bool, and NoneType represent individual values.
  • Immutable sequences: str stores characters and tuple stores fixed ordered items.
  • Mutable collections: list stores ordered items, while dict maps unique keys to values.
  • Set collections: set stores unique, unordered elements and supports union and intersection.
  • Selection principle: Use a list for changeable order, a tuple for a fixed record, and a dictionary for labelled lookup.

E. Type conversions

Type conversion creates a value of one type from a compatible value of another type.

  • Explicit conversion: int("42"), float("3.5"), and str(100) produce 42, 3.5, and "100".
  • Truncation: int(4.9) produces 4; it truncates toward zero rather than rounding.
  • Collection conversion: list("cat") produces ["c", "a", "t"].
  • Failure case: int("four") raises ValueError because the text is not a valid integer representation.
  • Implicit conversion: In 2 + 3.5, Python converts the integer-compatible value and returns 5.5.

F. Binary numbers

Binary represents numbers using base 2 and the digits 0 and 1.

  • Place values: Binary 1011 means (1×2^3 + 0×2^2 + 1×2^1 + 1×2^0 = 11).
  • Literal syntax: Python writes binary literals with 0b; therefore, 0b1011 evaluates to decimal 11.
  • Conversion: bin(11) returns '0b1011', while int("1011", 2) returns 11.
  • Bitwise operators: &, |, ^, ~, <<, and >> manipulate integer bit patterns.

G. String formatting

String formatting inserts values into readable text while controlling their presentation.

  • F-strings: f"{name} scored {score}" evaluates expressions inside braces.
  • Precision: If price = 12.5, f"{price:.2f}" produces "12.50".
  • Width and alignment: f"{name:<10}" left-aligns text in a field ten characters wide.
  • Alternatives: "{} scored {}".format(name, score) remains valid, but f-strings are generally clearer.
  • Representation conversion: f"{value!r}" uses repr(value), which is useful for debugging.

VI. Software Quality — Professional Coding Practices

A. Introduction to software development best practices

Software development best practices make programs easier to verify, maintain, and extend.

  • Decomposition: Divide a large task into small functions with focused responsibilities.
  • Version control: Git records changes and supports collaboration through commits and branches.
  • Testing: Automated tests compare actual behavior with expected results, such as verifying add(2, 3) == 5.
  • Error handling: Catch only anticipated exceptions and provide meaningful recovery or messages.
  • Security: Validate external input, avoid hard-coded secrets, and keep dependencies updated.
  • Documentation: Explain public interfaces, assumptions, inputs, and return values.

B. PEP 8

PEP 8 is Python’s principal style guide for consistently formatted source code.

  • Indentation: Use four spaces per indentation level rather than mixing spaces and tabs.
  • Naming: Use snake_case for variables and functions, CapWords for classes, and UPPER_CASE for constants.
  • Layout: Keep imports near the top, use blank lines to separate logical units, and avoid crowded expressions.
  • Whitespace: Write total = price + tax, not total=price+tax.
  • Purpose: PEP 8 promotes consistency; project-wide consistency may outweigh rigid application of every recommendation.

C. Code readability

Readable code communicates intent clearly to both its author and future maintainers.

  • Meaningful names: calculate_total() communicates more than calc() or f().
  • Simple control flow: Guard clauses and small functions reduce deeply nested logic.
  • Useful comments: Explain why an unusual decision exists, not what an obvious statement does.
  • Avoided duplication: Repeated logic should be moved into a reusable function.
  • Readable structure: Separate input, processing, and output so each stage can be understood and tested independently.

VII. Decision-Making Logic — Conditions and Boolean Evaluation

A. If-else statement

An if-else statement selects a block according to whether a condition is truthy or falsy.

  • Basic form: The if branch runs when its condition is true; otherwise, the else branch runs.
  • Multiple conditions: elif checks another condition only if earlier conditions failed.
  • Indentation: Every controlled block must be consistently indented.
PYTHON
if temperature > 30:
    status = "hot"
elif temperature >= 20:
    status = "warm"
else:
    status = "cool"

B. Equality and relational operators

Comparison operators examine relationships between values and return True or False.

  • Equality: == tests equal values, while != tests unequal values; assignment uses the different operator =.
  • Ordering: <, <=, >, and >= compare compatible ordered values.
  • Chaining: 0 <= score <= 100 is equivalent to testing both boundaries with and.
  • Floating-point caution: Calculated floats may require math.isclose(a, b) instead of exact equality.

C. Boolean operators and expressions

Boolean operators combine or negate conditions.

  1. Combination: and requires both operands to be truthy, whereas or requires at least one.
  2. Negation: not reverses truthiness; not True is False.
    • Short-circuiting: In x != 0 and 10 / x > 2, the division is skipped when x is zero.
    • Truthy and falsy values: 0, None, and empty collections are falsy; most other objects are truthy.

D. Order of evaluation

Precedence and associativity determine how an expression is grouped and evaluated.

  • General priority: Parentheses come first, followed by exponentiation, unary operators, multiplication-level operators, addition-level operators, comparisons, not, and, and or.
  • Associativity: Most binary operators group left to right, but exponentiation groups right to left.
  • Example: 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20.
  • Clarity rule: Use parentheses when grouping is not immediately obvious, even if precedence already gives the intended result.

E. Membership and identity operators

Membership tests collection contents, whereas identity tests whether two references designate the same object.

  1. Membership: in and not in search a container; "a" in "cat" is True.
  2. Identity: is and is not compare object identity, not merely equal values.
    • Equality contrast: Two separate lists can satisfy a == b while a is b is False.
    • Correct use: Use value is None for the singleton None; use == for ordinary value comparison.