Unit 1: Python basics
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
scoreandScoreare different. - Reserved keywords such as
if,for,def, andreturncannot be identifiers.
- Valid examples include
- Assignment: The statement
radius = 4binds the nameradiusto the integer object4; 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:
name = input("Name: ")
age = int(input("Age: "))
next_age = age + 1
print(name, "will be", next_age, "next year.")- Concrete interpretation:
namestores the text returned by the firstinput().agestores an integer produced by converting input text withint().next_ageis the value ofage + 1.- If the inputs are
Minaand19, the output isMina 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, and125.float: Represents floating-point numbers, such as3.14; binary representation means values such as0.1may not be stored exactly.complex: Represents numbers with real and imaginary parts, such as2 + 3j.bool: ContainsTrueandFalse; 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 asrange(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 valueNone, which commonly denotes the absence of a value.
- Type inspection and conversion:
type(value)returns the type ofvalue.int("12"),float("2.5"), andstr(40)explicitly convert compatible values.- Invalid conversion, such as
int("twelve"), raisesValueError.
- Arithmetic operators:
+,-, and*perform addition, subtraction, and multiplication./performs true division:7 / 2produces3.5.//performs floor division:7 // 2produces3.%gives the remainder:7 % 2produces1.**performs exponentiation:2 ** 3produces8.
- Comparison operators:
==,!=,<,<=,>, and>=produce Boolean results. Equality uses==; assignment uses=. - Logical operators:
andis true when both operands are truthy.oris true when at least one operand is truthy.notreverses 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" * 3gives"hahaha".inandnot intest membership:2 in [1, 2, 3]isTrue.
- Identity operators:
isandis nottest whether operands refer to the same object, not merely equal values. Usevalue is Nonefor aNonecheck, but usea == bfor ordinary value equality. - Assignment operators:
x += 3is an augmented assignment corresponding broadly tox = x + 3. - Precedence: Parentheses are evaluated first, followed broadly by exponentiation, unary operations, multiplication-level operations, addition-level operations, comparisons,
not,and, andor. Parentheses should make nontrivial intent explicit. - Worked example:
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, anddiscountdenote unit price, item count, and discount rate.subtotalis80.0 × 3 = 240.0.totalis240.0 × (1 − 0.10) = 216.0.eligiblebecomesTruebecause 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 throughbis then visible througha. - Floating-point limitation: Financial or exact decimal calculations may require
decimal.Decimalrather than binaryfloat. - Runtime errors: Division by zero raises
ZeroDivisionError, and incompatible operations can raiseTypeError.
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
ifstatement executes its block when its condition is truthy. Optionalelifbranches test further conditions, whileelsehandles the remaining case. - Condition ordering: Branches are tested from top to bottom, and only the first matching
if/elifbranch executes. whileloop: Repeats while a condition remains truthy; its body must normally change some state so that termination becomes possible.forloop: Iterates directly over an iterable such as a string, list, dictionary, orrange.range(start, stop, step)includesstartbut excludesstop.- Thus,
range(1, 5)produces1, 2, 3, 4.
- Loop-control statements:
breakimmediately exits the nearest enclosing loop.continueskips the remainder of the current iteration.passperforms 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:
total = 0
for number in range(1, 6):
if number == 4:
continue
total += number
print(total)- Execution trace:
numbersuccessively receives1,2,3,4, and5.- When
number == 4,continueprevents addition. totalbecomes1 + 2 + 3 + 5 = 11.
- Loop safety: An unintended infinite loop occurs when a
whilecondition never becomes false; for example, forgetting to update its counter. - Loop
elseclause: Anelseattached to a loop runs after normal completion but not when the loop ends throughbreak.
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:
defintroduces 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 aspower(base=2, exponent=3).
- Return value:
returnimmediately ends the call and sends a value to the caller. A function reaching its end withoutreturnreturnsNone. - 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:
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:
widthandheightare parameters representing rectangle dimensions.- The call supplies
5positionally and3through the keywordheight. - 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(), andround()are immediately available. - Module functions are accessed after importing, as in
math.sqrt(25).
- Built-ins such as
- Recursion: A recursive function calls itself and requires a base case that stops further calls; without one, Python eventually raises
RecursionError.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →