Unit 1: Basics of Python
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 = 10makesxan integer. - Object-based data model: Values such as integers, strings, lists, and functions are objects with types and associated operations.
- Case sensitivity:
total,Total, andTOTALare three different identifiers. - Indentation convention: Four spaces per indentation level is the standard convention.
- Comments: A
#begins a single-line comment. - Common workflow:
- Write instructions as Python source code.
- Execute them through an interpreter.
- Observe output or errors.
- Edit and rerun the code.
# 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.
-
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
.pyextension. - Execution: In the editor, Run → Run Module or
F5executes the current file. - Best use: IDLE is suitable for learning syntax, testing short statements, and creating small scripts.
-
Jupyter Notebook
- Notebook structure: A notebook consists of cells, usually either Code cells or Markdown cells.
- Cell execution:
Shift+Enterexecutes 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
.ipynbfiles. - Best use: Jupyter is effective for data analysis, demonstrations, calculations, and explanations combining code with formatted text.
-
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
.ipynbor.pyfiles. - 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.
language = "Python"
languageIn 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 asarea.py; avoid naming a file after standard modules such asmath.py. - Execution in IDLE: Save the file and press
F5or select Run Module. - Execution in a terminal: Navigate to the file’s directory and issue an appropriate command.
python area.pyOn 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.
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()orfloat(). - 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:
sepchanges the separator between printed values.endchanges the characters printed at the end.
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, or4500.float: Represents floating-point values, such as3.14or-0.5; binary representation can cause approximations such as0.1 + 0.2.complex: Represents numbers of the form (a+bj), whereais the real part,bis the imaginary coefficient, andjdenotes the imaginary unit.- Boolean relationship:
boolis a subclass ofint;Truebehaves numerically like1, andFalselike0. - Inspection:
type(value)reports a value’s type. - Conversion:
int(4.8)gives4, whilefloat(6)gives6.0; integer conversion truncates rather than rounds.
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 / 2produces3.5.//performs floor division:7 // 2produces3.%gives the remainder:7 % 2produces1.**performs exponentiation:2 ** 3produces8.
- Comparison operators:
==,!=,<,>,<=, and>=returnTrueorFalse. - Logical operators:
and,or, andnotcombine or reverse Boolean conditions. - Assignment operators:
=,+=,-=,*=, and similar forms update variables;x += 2meansx = x + 2. - Membership operators:
inandnot intest membership, as in"P" in "Python". - Identity operators:
isandis nottest 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, andor.
result = (5 + 3) * 2 ** 2
print(result) # 32Parentheses 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.
ifbranch: Executes when its condition is true.elifbranch: Tests another condition only when preceding conditions were false.elsebranch: 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
if–elif–elsechain, only the first matching branch executes.
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.
-
forloop- Principle: Iterates over elements of a sequence or another iterable.
- Range generation:
range(start, stop, step)generates integers fromstartup to, but not including,stop. - Concrete case:
range(1, 4)produces1,2, and3.
-
whileloop- 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:
breakterminates the nearest loop immediately.continueskips the remainder of the current iteration.passperforms 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.
total = 0
for number in range(1, 6):
total += number
print(total) # 15The 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:
returnends the function and sends a result to the caller; without it, the function returnsNone. - Local scope: Variables assigned inside a function are normally local and unavailable outside it.
- Default parameters: A declaration such as
power=2supplies 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.
def rectangle_area(length, width=1):
"""Return the area of a rectangle."""
return length * width
area = rectangle_area(6, 4)
print(area) # 24Here, 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.
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 →