Programming in Python · Lessons 1–4
Programming in Python Study Guide: Lessons 1–4
Review computational thinking, programming tools, variables, literals, numeric data, expressions, and formatted Python output for Lessons 1–4.
How to use this guide
This guide condenses Lessons 1–4 into the vocabulary, comparisons, and code patterns that support early Python problem solving. Read the lesson sections in order, trace every example by hand, and then write a small variation without copying it.
Study in this order:
- Explain each bold term in your own words.
- Compare the terms that are easy to confuse.
- Predict what each code sample displays before running it.
- Practice changing the input, operator, data type, or formatting rule and explain the result.
The ideas that connect Lessons 1–4
The lessons form one workflow: reason about a problem, express the solution with programming tools, represent information with names and values, and use operators to produce a result. Computational thinking supplies the plan; an editor, interpreter, shell, or IDE helps you implement and test it; variables and literals represent the data; and expressions transform that data.
Keep these distinctions connected:
- An algorithm is the logic and finite steps for solving a problem; a program expresses those instructions in a programming language.
- A literal is a value written directly in code; a variable is a name that refers to stored data; a constant is a named value intended not to change.
- A syntax error prevents Python from understanding the form of a statement; a runtime error occurs while the program runs; a logic or semantic error produces an unintended meaning or result.
- Type conversion changes a value’s data type; formatting changes how a value is displayed without changing the stored value.
Lesson 1 — Computational Thinking
Algorithms and programs
An algorithm is a finite series of clear, precise steps for solving a problem or completing a task. A dependable algorithm has:
- Input: the starting data it is allowed to receive.
- Output: one or more results it produces.
- Finiteness: a stopping point; it does not continue forever.
- Precision: steps that are unambiguous.
- Effectiveness: steps that can be carried out and produce a correct result.
A computer program is a set of instructions that performs a task when executed by a digital device. The algorithm is the underlying logic; Python is one way to express that logic. More than one algorithm can solve the same problem, so computer scientists compare algorithms for efficiency, speed, reliability, and maintainability. A standard algorithm is a known, reusable solution pattern; when one is not available, a programmer can work through the task manually, record the steps, and analyze them to formulate a new algorithm.
Decomposition
Decomposition divides a complex problem or application into smaller, manageable parts. It reduces cognitive load and makes programs easier to develop, test, maintain, and improve.
| Type | What to identify | Example |
|---|---|---|
| Structural decomposition | A hierarchy of building-block units; usually nouns | Divide a banking app into accounts, transfers, authentication, and notifications |
| Functional decomposition | Actions, processes, or steps; usually verb phrases | Prompt for credentials → validate them → generate a PIN → display a result |
| Object-oriented decomposition | Logical and physical objects that the program manipulates, plus their attributes and methods | Identify a Customer, Account, and Transfer object |
Good decomposition minimizes dependencies between parts and maximizes cohesion within each part. Dependencies are connections that make one part rely on another. Cohesion is how closely the responsibilities within one part belong together. An effective breakdown minimizes dependencies and maximizes cohesion.
Functional decomposition should continue until each step is specific enough to become a clear algorithm step. For example, “validate credentials” may need to be decomposed into comparing a user ID and password, checking the result, and deciding what happens next.
Pattern identification
Pattern identification finds similarities in procedures, tasks, or data so that a reusable solution can be designed.
- A fill-in-the-blank pattern uses a placeholder for a value that changes. A variable can represent many different numbers instead of writing a separate solution for each number.
- A repetitive pattern is an action or process that occurs again and again, such as allowing three password attempts before locking an account.
- A classification pattern groups objects that share attributes. A class such as
Restaurantcan describe a restaurant name, hours, and menu; a single restaurant is an object created from that template.
Abstraction and black boxes
Abstraction hides unnecessary detail, simplifies complexity, and substitutes a general idea for something specific. It helps a solution work with a wide variety of data, but abstracting away too much detail can make a program too vague or unusable.
A class can serve as an abstraction when it represents a recognized pattern of attributes. For example, a LoginCredentials class can describe shared fields such as user_id, password, and mobile_number without describing every individual user. Abstraction can also help identify likely variables: pattern recognition finds possible variables, and object-oriented design organizes those variables into objects and attributes.
A black box accepts input, processes it, and produces output while hiding its internal implementation. The user needs to know the interface—what to provide and what comes back—not every internal step. Python’s built-in functions are familiar black boxes.
Lesson 1 terms to know
algorithm, program, input, output, finiteness, precision, effectiveness, efficiency, standard algorithm, decomposition, structural decomposition, functional decomposition, object-oriented decomposition, dependency, cohesion, pattern identification, fill-in-the-blank pattern, repetitive pattern, classification pattern, class, object, attribute, method, abstraction, black box
Lesson 2 — Programming Tools
Source code, editors, and languages
Source code is human-readable text that expresses a program. A program editor or code editor is designed for entering high-level code without adding the extraneous formatting symbols used by a word processor. Useful editor features include syntax coloring, indentation, search, line numbers, and error highlighting. A programming language provides the vocabulary and rules for specifying procedures a digital device should perform.
print("Hello, Python!")
The Hello World! program is a common first program because it confirms that the language, editor, and execution process are working. A language may use different keywords, but programming languages commonly provide arithmetic operators for calculations. Do not assume that every language uses the same keyword, punctuation, or braces.
Interpreter, shell, IDE, and SDK
An interpreter reads source code and executes it. Python’s interactive shell, also called a REPL (read-evaluate-print loop), is useful for quickly testing individual lines or expressions. A saved .py file is better for a complete, repeatable, shareable program.
When Python is installed, it includes IDLE, a small integrated development and learning environment. Use IDLE’s shell mode for quick tests. Use its editor/script mode when saving a program for future use; save the file and run it, commonly with F5.
An integrated development environment (IDE) combines tools such as a code editor, project or file browser, run controls, interpreter configuration, compiler or build support when needed, linking, and debugging. IDEs may be desktop applications or web-based environments; they are not limited to local desktop use.
A software development kit (SDK) is a set of tools for developing software for a particular platform. An iOS SDK can include an iPhone simulator. An SDK and an IDE can work together, but they are not the same thing: the SDK supplies platform-specific tools and libraries, while the IDE supplies an integrated workspace.
Build tools and program translation
The three broad tool groups programmers need are coding tools, build tools, and debugging tools.
- Coding tools help write source code.
- Build tools prepare source code for execution. A compiler translates source code into object code; a linker combines object code and libraries into an executable program. A preprocessor handles preliminary substitutions or directives before compilation.
- Debugging tools help locate and correct errors. Breakpoints pause execution, and program animation or step-by-step execution shows how the program moves through its statements.
Object code is the code produced by a compiler. Executable code is stored in a runnable file that the microprocessor can execute. Some languages produce bytecode, an intermediate form that a virtual machine can run or translate for a host platform. For example, the Java Virtual Machine converts Java bytecode into instructions that work on the host platform.
Syntax, runtime, logic, and semantic errors
Use this table to distinguish error categories:
| Error | What happens | Example |
|---|---|---|
| Syntax error | Python cannot parse the form of the statement | A missing quote, parenthesis, colon, or required keyword |
| Runtime error | The program starts but fails during execution | Dividing a number by zero or opening a file that does not exist |
| Logic error | The program runs but produces the wrong result | Subtracting when the intended operation was addition |
| Semantic error | A statement is syntactically valid but its meaning or operation is wrong | Using the wrong comparison or arithmetic operator in a decision |
Syntax concerns the order and punctuation required by the language. Semantics concerns the meaning and validity of statements. A debugging utility does not translate error messages into another language, and debugging does not mean removing comments; debugging means finding and correcting problems.
Directives, reserved words, and workflow
A reserved word is a word the language reserves for a special purpose, such as if, for, or class. A directive tells the computer or a development tool how to handle the program or its translation. Comments document code and are ignored during execution.
Use a repeatable workflow: write a small change, save it, run it, inspect the output or traceback, test another input, and revise. Test normal cases, boundary cases, and invalid cases. A program that runs without a syntax error can still contain a runtime, logic, or semantic error.
Lesson 2 terms to know
source code, program editor, code editor, programming language, interpreter, REPL, shell mode, IDLE, IDE, SDK, coding tools, build tools, debugging tools, compiler, preprocessor, linker, object code, bytecode, executable code, JVM, syntax, semantics, syntax error, runtime error, logic error, semantic error, breakpoint, comment, reserved word, directive
Lesson 3 — Literals, Variables, and Constants
Literals and primitive data
A literal is a data value written directly in program code. Common primitive data categories include characters, strings, integers, floating-point numbers, and Boolean values. A character literal represents one character; a string literal represents letters, symbols, words, or sentences and is enclosed in single or double quotes. Boolean literals are True and False without quotation marks.
count = 7 # integer literal
temperature = -4.5 # floating-point literal
symbol = '@' # character/string literal
message = "Ready" # string literal
is_valid = True # Boolean literal
Digits are not automatically quantities. A ZIP code, PIN, area code, or last four Social Security digits is often better represented as a string because it is an identifier, not a value used in arithmetic; leading zeros must be preserved. A composite data type combines related pieces of data into one structure. Time, dates, addresses, and records are common examples. Primitive types are the simpler built-in pieces from which larger data structures can be organized.
Variables, constants, and memory
A variable is a named memory location that holds data which may change. The variable name gives the program a readable reference to the stored value. A constant is a named location that holds a value the program intends not to change; constants make later code easier to understand and update.
Python uses uppercase names with underscores for constants, such as DAYS_IN_WEEK = 7. This is a convention, not a language-enforced read-only rule. Use descriptive names with snake_case in this course. camelCase is another naming style; Red_Sox_Inventory_Count is neither the usual camel case nor the usual snake case.
DAYS_IN_WEEK = 7
hours_studied = 2
minutes_studied = hours_studied * 60
A literal is the value itself. A variable or constant is a name that refers to stored data. Do not confuse either one with the memory address or with the data type that describes the value.
Declaration, initialization, assignment, and type inference
Declaration associates a name with a variable or memory location. Initialization gives a variable its first value. Assignment stores a value in a name and can change that value later. In Python, the first assignment both creates and initializes a variable; Python does not require a separate type declaration.
score = 0 # first assignment initializes score
score = 10 # later assignment changes score
score = score + 5 # reads 10, then stores 15
Python uses type inference and dynamic typing: the value assigned to a name determines its current type, and the same name can later refer to a value of another type.
response = None # no value is available yet
response = 42 # now an integer
response = "forty-two" # now a string
None means no value or no available value; it is not the same as numeric zero. Using a name before it has been assigned causes an error. Assignment statements and initialization have the same visible form, but later assignment can change a variable’s value.
Input, output, and pseudocode
The general algorithm for collecting user data is:
- Initialize a variable to hold the user’s input.
- Prompt the user to enter data.
- Collect the data in the initialized variable.
In Python, input() returns a string even when the user types digits. Convert the response before using it in arithmetic. print() displays the values supplied to it; it does not display variable names unless the names are placed inside a quoted string.
number_of_chocolates = 0
number_of_chocolates = int(input("How many chocolates would you like? "))
print("You would like", number_of_chocolates, "chocolates.")
When pseudocode says to display text, a variable, and more text, the variable’s current value appears in the output. If turkey_sandwich_meal_count is 2, the result is equivalent to:
You would like 2 turkey sandwich meals today, correct?
Lesson 3 terms to know
literal, character literal, string literal, Boolean literal, integer, floating-point, primitive data type, composite data type, variable, constant, declaration, initialization, assignment, memory location, type inference, dynamic typing, None, snake_case, camelCase, input(), print(), pseudocode
Lesson 4 — Numeric Data Types and Expressions
Integers and floating-point values
An integer is a whole number without a decimal fraction. It may be positive, negative, or zero and can be written in decimal, binary, or hexadecimal notation.
decimal_number = 23
negative_number = -363
binary_number = 0b00000101
hex_number = 0x6C
Python integers are signed and can grow beyond a fixed one-byte or four-byte range as needed. Do not assume a Python integer uses exactly one byte or that one byte can represent every value from -255 through 255.
A floating-point value contains a decimal point or uses E notation. Floats can be positive or negative. Python stores floating-point values in an approximate binary representation; E notation is a way of writing a number, not the storage format itself. A floating-point representation includes a sign, exponent, and significant data. Binary approximation is why rounding errors can occur.
price = 19.99
rate = 0.08
scientific = 4.5967e2
Arithmetic operators and expressions
An expression combines values, variables, and operators to produce a value.
| Operation | Python operator | Example |
|---|---|---|
| Addition | + |
7 + 2 gives 9 |
| Subtraction | - |
7 - 2 gives 5 |
| Multiplication | * |
7 * 2 gives 14 |
| Division | / |
7 / 2 gives 3.5 |
| Floor division | // |
7 // 2 gives 3 |
| Modulo/remainder | % |
7 % 2 gives 1 |
| Exponentiation | ** |
7 ** 2 gives 49 |
Use % for a remainder or an even/odd test. Use // when discarding the fractional portion is intentional. Compound operators provide shortcuts for common operations:
total = 10
total += 5 # total = total + 5
total *= 2 # total = total * 2
total %= 3 # total = total % 3
Order of operations
Python evaluates arithmetic in this order:
- Parentheses.
- Exponentiation and roots.
- Multiplication, division, floor division, and modulo from left to right.
- Addition and subtraction from left to right.
For example, 9 + 4 * 6 / 2 evaluates to 21. To produce 39, group the addition first:
(9 + 4) * 6 / 2
Parentheses make the intended calculation visible and can change the result without changing the individual operators.
Coercion and type conversion
Coercion is Python’s automatic choice of a compatible type during an operation. Type casting is an explicit conversion requested by the programmer. Use a conversion when the data must be stored or used in another type, such as storing an average from normal division as a whole number.
whole = 7
decimal = 2.5
result = whole + decimal # automatic numeric coercion produces a float
truncated = int(4.9) # 4; int() removes the fractional part
converted = float(7) # 7.0
int() truncates toward zero; it does not round to the nearest integer. Multiplying an integer and a float or dividing a float by an integer does not normally require a manual conversion.
Formatting output
Formatting changes the display of a value without changing the value stored in a variable. Python output formatting can specify width, alignment, precision, and type.
price = 4.43050
print("Price: ${:.2f}".format(price))
print("Count: {:d}".format(7))
print("Right aligned: {:>10}".format(42))
print("Three in the middle: {:^5}".format(3))
In a format field, ^ centers a value, > right-aligns it, and a number such as 5 sets the field width. A precision such as .2f displays two digits after the decimal point. Formatting preserves the underlying value, while converting a float to an integer can discard fractional information.
Lesson 4 terms to know
data type, integer, floating-point, E notation, signed integer, binary, hexadecimal, expression, operand, operator, division, floor division, modulo, compound operator, order of operations, coercion, type casting, int(), float(), rounding error, width, alignment, precision, formatting, format()
Course Notes