Unit 1: Python Environment Setup and Basics
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
.pyfiles 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
pythonworks in a terminal. - Verification: Check the installed interpreter and package manager with
python --versionandpip --version. - Anaconda: A distribution containing Python, scientific libraries, Jupyter, and the
condaenvironment 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:
python -m venv .venvB. 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 * 6at the>>>prompt immediately returns42, making the shell useful for experimentation. - Script file: A file such as
hello.pystores reusable instructions:
price = 25
quantity = 4
print(price * quantity)- Execution: Run the file from its directory with
python hello.py; the program prints100. - 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 + 5performs an assignment; a newline generally ends the statement. - Indentation: A colon introduces an indented suite after constructs such as
if,for, anddef. - Case sensitivity:
score,Score, andSCOREare 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 = 20binds the nameageto the integer object20. - 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_casenames, such asstudent_count, rather than unclear names such asx1.
C. Data types
A data type determines a value’s representation and the operations it supports.
- Numeric types:
intrepresents arbitrary-precision integers,floatrepresents floating-point values, andcomplexrepresents numbers such as2 + 3j. - Logical type:
boolhas the valuesTrueandFalse. - Sequence types:
str,list, andtuplestore ordered items. - Other types:
dictstores key-value pairs,setstores unique elements, andNoneTypehas the single valueNone. - 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 += 2is a compact form ofx = x + 2. - Comparison: Operators such as
<and==produce Boolean results. - Context dependence:
3 + 4gives7, 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.5andquantity = 4, the expression evaluates to50.0. - Statement distinction:
2 + 3is an expression;result = 2 + 3is an assignment statement containing that expression. - Composition: Function calls can be nested, as in
round(abs(-3.7)), which evaluates to4.
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:
sepchanges the separator andendchanges the ending, for exampleprint("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 randomloads the module and permits qualified access such asrandom.randint(1, 6). - Selective import:
from math import sqrtallows the direct callsqrt(25). - Aliases:
import statistics as statscreates a shorter module name. - Namespace benefit: Qualified names such as
math.pishow 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.pirepresents π andmath.erepresents Euler’s number. - Functions:
math.sqrt(81),math.ceil(2.1), andmath.floor(2.9)return9.0,3, and2. - Angles: Trigonometric functions use radians;
math.radians(180)converts 180 degrees to π radians. - Limitation:
math.sqrt(-1)raises an error; complex-number operations require thecmathmodule.
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:
\nrepresents a newline,\ta 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"andword[-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)returns6,"Py" in wordreturnsTrue, andword.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(), andpop()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, andNoneTyperepresent individual values. - Immutable sequences:
strstores characters andtuplestores fixed ordered items. - Mutable collections:
liststores ordered items, whiledictmaps unique keys to values. - Set collections:
setstores 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"), andstr(100)produce42,3.5, and"100". - Truncation:
int(4.9)produces4; it truncates toward zero rather than rounding. - Collection conversion:
list("cat")produces["c", "a", "t"]. - Failure case:
int("four")raisesValueErrorbecause the text is not a valid integer representation. - Implicit conversion: In
2 + 3.5, Python converts the integer-compatible value and returns5.5.
F. Binary numbers
Binary represents numbers using base 2 and the digits 0 and 1.
- Place values: Binary
1011means (1×2^3 + 0×2^2 + 1×2^1 + 1×2^0 = 11). - Literal syntax: Python writes binary literals with
0b; therefore,0b1011evaluates to decimal11. - Conversion:
bin(11)returns'0b1011', whileint("1011", 2)returns11. - 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}"usesrepr(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_casefor variables and functions,CapWordsfor classes, andUPPER_CASEfor constants. - Layout: Keep imports near the top, use blank lines to separate logical units, and avoid crowded expressions.
- Whitespace: Write
total = price + tax, nottotal=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 thancalc()orf(). - 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
ifbranch runs when its condition is true; otherwise, theelsebranch runs. - Multiple conditions:
elifchecks another condition only if earlier conditions failed. - Indentation: Every controlled block must be consistently indented.
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 <= 100is equivalent to testing both boundaries withand. - 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.
- Combination:
andrequires both operands to be truthy, whereasorrequires at least one. - Negation:
notreverses truthiness;not TrueisFalse.- Short-circuiting: In
x != 0 and 10 / x > 2, the division is skipped whenxis zero. - Truthy and falsy values:
0,None, and empty collections are falsy; most other objects are truthy.
- Short-circuiting: In
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, andor. - Associativity: Most binary operators group left to right, but exponentiation groups right to left.
- Example:
2 + 3 * 4is14, while(2 + 3) * 4is20. - 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.
- Membership:
inandnot insearch a container;"a" in "cat"isTrue. - Identity:
isandis notcompare object identity, not merely equal values.- Equality contrast: Two separate lists can satisfy
a == bwhilea is bisFalse. - Correct use: Use
value is Nonefor the singletonNone; use==for ordinary value comparison.
- Equality contrast: Two separate lists can satisfy
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 →