Computer and Python Basics
Introduction to Programming and Python
Programming as a Skill
Programming is a practical skill, like mathematics or reading: it develops through repeated use. Watching someone write code is not enough to build the ability to solve problems independently. Students need regular practice writing, running, and debugging programs.
An introductory programming course develops three related abilities:
Conceptual knowledge: understanding computer science ideas and how programs work.
Programming skill: expressing instructions in a programming language.
Problem-solving skill: turning a problem described in everyday language into a computational solution.
A useful habit is to ask whether computation can help solve a problem, rather than relying only on manual or mathematical methods. This way of approaching problems is called computational thinking.
Programming practice also involves learning to organize code so it is readable and modular. Algorithms—the step-by-step methods that programs use—provide solutions to particular problems. Comparing algorithms leads to questions of algorithmic complexity: how efficiently a program uses time and memory.
From Facts to Procedures
Declarative and imperative knowledge
Declarative knowledge states a fact or describes a relationship. For example:
The square root of x is a number y such that y2=x.
This definition describes what a square root is, but it does not tell a computer how to find one.
Imperative knowledge gives a procedure: a sequence of instructions for accomplishing a task. Programming primarily expresses imperative knowledge. A program tells the computer what steps to perform.
Example: an iterative square-root algorithm
A simple method for estimating the square root of a positive number x starts with a guess g and repeatedly improves it:
Check whether g2 is sufficiently close to x. If it is, stop.
Otherwise, calculate a better guess:
gnew=21(g+gx)Use gnew as the next guess and repeat.
For example, to estimate 16, begin with g=3. The update gives:
Repeating the update brings the estimate closer to 4.
This procedure illustrates three essential features of an algorithm:
A sequence of steps: instructions are performed in an order.
Flow of control: conditions and repetition determine which steps happen next.
Termination: a stopping condition prevents the procedure from continuing indefinitely.
The stopping condition can specify how accurate the answer must be. For instance, an algorithm might stop when the estimate is within a chosen tolerance of the actual answer.
Recipes have a similar structure. They give ordered steps, may include conditions or repetition, and specify when the task is complete. A computer executes algorithms in the same procedural sense: it follows the instructions it has been given.
What Computers Do
Computers are powerful at tasks such as storing large quantities of data and performing operations quickly. They do not independently understand a problem or decide what a person meant. They carry out instructions.
A computer follows the instructions it is given; it does not automatically infer the programmer’s intentions.
This principle explains why a program can produce a result that is wrong for its intended purpose while still doing exactly what its instructions specify.
A simplified model of a computer
A basic view of a computer includes:
Memory: stores values and instructions at locations.
Arithmetic logic unit (ALU): performs operations such as addition, subtraction, and comparisons.
Control unit: coordinates instruction execution. A program counter tracks which instruction is to be performed.
For example, a low-level instruction sequence could tell a computer to:
Read values from two memory locations.
Send them to the ALU to be added.
Store the result at another memory location.
Compare that result with a second value.
Print the result of the comparison.
Even a small calculation can require many explicit instructions at this level. High-level programming languages make such instructions easier for people to express.
Fixed-program and stored-program computers
A fixed-program computer, such as a basic calculator, performs a predefined set of operations. A user can enter values and combine operations, but the device does not generally store an arbitrary instruction sequence for later use with new inputs.
A stored-program computer can store instructions in memory as data. An interpreter or other execution mechanism reads those instructions and carries them out. Basic operations include arithmetic, logical tests such as checking whether two values are equal, and moving data between memory locations.
Computation across programming languages
A theoretical result associated with Alan Turing is that a sufficiently capable computing system can perform any computation expressible in another sufficiently capable programming language. A Turing-machine model illustrates this using a tape and a small set of basic actions, such as moving along the tape, reading or writing a value, erasing a value, or doing nothing.
The practical significance is that programming languages can differ greatly in appearance and convenience while still being able to express the same kinds of computations. Higher-level languages provide useful operations that save programmers from spelling out every low-level step.
Programming Languages: Building Blocks and Meaning
Programming languages, like natural languages, have building blocks and rules for combining them. The analogy is useful, but programming languages are more precise: a program has a defined interpretation rather than several possible meanings.
Primitives
A language’s primitives are its basic building blocks. In Python, these include:
Values such as numbers and sequences of characters.
Operators such as addition, multiplication, and division.
Tests such as equality comparisons.
Primitives can be combined into larger expressions and programs.
Syntax
Syntax is the set of rules governing how language elements can be arranged. In English, a sequence of nouns alone may not form a sentence, while a noun–verb–noun pattern often does. Programming languages likewise require expressions to follow specific structural rules.
For example, placing a string and a number side by side without an operator is not a meaningful Python expression. Adding the multiplication operator between the string "Hi" and the number 5 forms a valid expression: it means to repeat the string five times.
Static semantics
An expression can be syntactically well-formed but still not make sense under the language’s rules for types and operations. These rules are part of static semantics.
For example, Python permits a string to be multiplied by an integer, so the multiplication has a defined meaning. But adding a string and an integer does not have the intended ordinary meaning, even if the expression has the general shape of an operator applied to two values. Such combinations produce errors.
Program semantics and errors
Semantics concerns what a program means when it runs. Unlike a sentence in natural language, a program’s instructions have a defined operational interpretation. The computer follows that interpretation, even when it differs from what the programmer intended.
Several kinds of problems can arise:
Syntax errors: the program violates the language’s structural rules, such as through invalid punctuation or indentation.
Static-semantic errors: an operation or value combination is invalid under the language’s rules.
Behavioral or logic errors: the program runs, but its behavior does not match the programmer’s intention. It may produce an incorrect result, stop unexpectedly, or fail to terminate.
Logic errors are often especially frustrating because the computer may execute the program without reporting a syntax problem. The challenge is then to determine why the program’s actual behavior differs from the intended behavior.
Objects, Types, and Values
At its core, programming involves creating objects and manipulating them. Every object has a type, which determines what kinds of operations are appropriate for it.
For example, a number can take part in arithmetic. A string, which is a sequence of characters, supports different operations, such as finding its length or accessing one of its characters. Trying to divide one string by another is not a meaningful operation in Python.
Scalar and non-scalar objects
Scalar objects are basic values without an internal collection structure, such as numbers and Boolean values.
Non-scalar objects have internal structure. A list, for example, contains multiple elements arranged in a sequence.
Basic Python types
Integer (
int): whole numbers, such as 5, 0, or −100.Float (
float): numbers represented with a decimal point, such as 3.27 or 2.0.Boolean (
bool): truth values, which areTrueandFalse. Their capitalization matters.NoneType: the type of the single special value
None, used to represent the absence of a value in some contexts.
The type indicates which operations are allowed, not how many objects of that type exist. Integers and floats can represent many different values; the Boolean type has only two values, and NoneType has only one.
Checking an object’s type
Python’s type command reports the type of an object. For example:
type(7) # int
type(0.0) # float
type(True) # boolCapitalization is significant in Python. True is the Boolean value, while true is not recognized as the same built-in value and can produce a name error.
Type Conversion
Type conversion, or casting, creates a value of another type from an existing value. It does not change the original object; instead, it produces a converted value.
float(3) # 3.0
int(5.2) # 5
int(5.9) # 5Converting a float to an integer with int truncates the fractional part; it does not round to the nearest integer. For positive values, this leaves the integer portion. More generally, integer conversion truncates toward zero.
Rounding is a separate operation. In Python, round(5.9) returns the integer 6. The result’s type can matter in later operations, so checking types in the interactive shell can help clarify what a conversion or operation produced.
Expressions and Operators
An expression combines values, operators, and sometimes function calls to produce a value. For example, 3+2 evaluates to 5.
Python evaluates an expression to a result; it does not preserve the expression as a stored calculation that automatically updates later. If a program uses a result again, it can assign that result to a variable.
Expressions may be nested, and they can be used wherever a value is expected, including as an argument to type or to a conversion function.
Arithmetic operators and result types
For ordinary arithmetic with integers and floats:
Addition, subtraction, and multiplication: when both operands are integers, the result is generally an integer. If either operand is a float, the result is generally a float.
True division (
/): produces a float, including when the division has a whole-number result.Floor division (
//): gives the floor of the quotient. For positive integers, this is the whole-number quotient.Remainder (
%): gives the remainder from division. For example, 5mod3=2.Exponentiation (
**): raises one value to the power of another. In mathematical notation, 23=8.
For example, 5/3 produces a float, while 5//3 gives the floor-division result and 5%3 gives the remainder. With nonnegative integers, the floor-division result and remainder satisfy:
The types of results depend on the operands and the operation. A decimal-point operand generally causes arithmetic results to be represented as floats; true division returns a float by definition.
Operator precedence
Python evaluates operators according to precedence rules. Exponentiation is evaluated before multiplication, division, floor division, and remainder; those operators are evaluated before addition and subtraction. Parentheses can make the intended order explicit or override the default precedence.
For example, parentheses determine which part of an expression is evaluated first. When commands or functions are nested, the inner expression is evaluated to produce an argument for the outer command.
Variables and Assignment
A variable is a name associated with a value. Variables make programs easier to write and read because a meaningful name can stand for a value used repeatedly.
For example, a program can assign a value to pi and then use that name in calculations instead of repeatedly writing a long decimal approximation.
Assignment is not mathematical equality
In mathematics, an equation such as x=y states a relationship that may be true or false. In Python, the equals sign in an assignment statement performs an action: it associates a name on the left with the value produced on the right.
An assignment has one variable name on the left and a value-producing expression on the right:
m = 10
f = m * 9.98Python evaluates the right-hand side first. Since m has the value 10, the second line calculates 99.8 and associates that result with f.
An assignment must have an assignable name on the left. A literal value or an expression such as a multiplication cannot serve as the variable name. Multiple characters can form a name, so xy is a valid variable name.
Choosing meaningful names and using comments
Good variable names communicate what values represent. Names such as radius and area make a program easier to understand than names consisting only of unrelated single letters.
A comment is text for human readers that Python does not execute. A comment beginning with # can explain a section’s purpose. Comments are most useful when they describe why a block of code exists or what it accomplishes, rather than simply restating an obvious operation.
Readable code combines descriptive names with useful comments. For example, a comment can explain that a section calculates the area and circumference of a circle using an approximation of π, while the code itself shows the detailed arithmetic.
Rebinding Variables and Execution Order
A variable can be rebound: its name can be associated with a different value later in the program.
Consider:
radius = 2.2
radius = radius + 1Python evaluates the right-hand side of the second assignment using the current value of radius. It calculates 2.2+1=3.2, then associates radius with 3.2. The name no longer refers to 2.2.
The earlier value may remain in memory temporarily, but the variable name no longer provides access to it. If no references to an object remain, Python may reclaim its memory through garbage collection.
Assignments do not automatically update dependent values
Suppose area is calculated from radius, and then radius is changed. The existing value of area does not automatically recalculate. The computer follows the written instructions; it does not infer that one value should be updated whenever another changes. The program must explicitly calculate area again if that is required.
In the absence of branching or repetition, Python executes program statements in order, one after another.
This line-by-line execution model is essential for understanding assignments and debugging. Each statement uses the values available at the moment that statement runs.
Swapping Two Values
Reassigning one variable directly from another can lose a value that needs to be preserved. Suppose x is 1 and y is 2. The following sequence does not swap them:
y = x
x = yAfter the first assignment, both names refer to the value 1. The original value of y—2—has been lost from those variable bindings.
A temporary variable preserves one value while the other is reassigned:
temp = y
y = x
x = tempThe steps are:
Store the original value of
yintemp.Assign the original value of
xtoy.Assign the saved value in
temptox.
The result is that x holds the original value of y, and y holds the original value of x.
Interactive Tools and Debugging
Programs can be written in a file editor and executed, but an interactive shell is useful for testing short commands. It can help check a type, evaluate a small expression, or try an assignment without creating a complete program.
A step-by-step visualizer such as Python Tutor can help with more complex code. It displays the program’s execution one statement at a time and shows the values associated with variables after each step. This makes it easier to detect when a value changes, when a variable is rebound, or why a later calculation uses an unexpected value.
The central ideas are that Python objects have types, expressions evaluate to values, assignment binds names to values, and program statements execute in order. Understanding these ideas provides a foundation for writing and debugging more complex programs.

Ask anything
We've read this whole study set, so questions about it get the best answers.