Python Programming Fundamentals: The Way of the Program, Variables, Expressions & Statements
Introduction to Course
Objective: To teach you to think like a computer scientist.
Computer Scientist's Thinking: Combines some of the best features of mathematics, engineering, and natural science.
Like mathematicians: Computer scientists use formal languages to denote ideas (specifically, computations).
Like engineers: They design things, assembling components into systems and evaluating trade-offs among alternatives.
Like scientists: They observe the behavior of complex systems, form hypotheses, and test predictions.
The Single Most Important Skill: Problem-solving.
Problem-solving means: The ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately.
Learning to Program: An excellent opportunity to practice problem-solving skills, hence the chapter title "The Way of the Program".
Dual-level learning: You will learn programming as a useful skill, and also use it as a means to an end, the purpose of which will become clearer.
What is a Program
Definition: A sequence of instructions that specifies how to perform a computation.
Scope of Computations: Can be mathematical (e.g., solving systems of equations, finding polynomial roots) or symbolic (e.g., searching and replacing text, processing images, playing video).
Basic Instructions (found in almost every programming language):
Input: Getting data from devices such as the keyboard, a file, or the network.
Output: Displaying data on the screen, saving it in a file, or sending it over the network.
Math: Performing fundamental mathematical operations like addition and multiplication.
Conditional execution: Checking for specific conditions and executing appropriate code blocks based on those conditions.
Repetition: Performing an action multiple times, often with some variation through each iteration.
Programming Concept: Programming involves breaking down a large, complex task into smaller, simpler subtasks that can be accomplished using these basic instructions.
Running Python
Python Versions: This course uses Python 3 , which offers improved features but is not entirely backward compatible with Python 2. Differences will be highlighted.
Setup Recommendation: Install Python 3 using Anaconda's free Python distribution.
Anaconda: Available for Linux, Windows, and Mac. Includes popular Python packages and useful tools.
Installation: Typically installs in your home directory, avoiding the need for administrator privileges.
Version: At the time of writing, Python 3.8 was current, but use the Python 3.x version recommended for the course.
Learning Strategy: Hands-on practice is crucial. Try out examples as you go, as programming is an active skill similar to playing an instrument.
Python Interpreter Prompt: The symbol
>>>
signifies that the Python interpreter is ready to accept Python code. Code entered after>>>
is executed, and any resulting output is displayed on the next line.
The First Program: "Hello, World!"
Traditional Introduction: The first program in a new language is typically "Hello, World!" which simply displays this phrase.
Python Example (Interactive Mode):
python >>> print('Hello, World!') Hello, World!
print
** Statement**: In Python,print()
is used to display output on the screen, not to print on paper.Quotation Marks: The single quotes surrounding
'Hello, World!'
mark the beginning and end of the text (string) to be displayed. They themselves do not appear in the output.Parentheses: In Python 3 , the parentheses
()
afterprint
signify thatprint
is a function (to be covered in Chapter 3).Python 2 Difference: In Python 2,
print
was a statement and did not require parentheses:>>> print 'Hello, World!'
Arithmetic Operators
Operators: Special symbols used to represent computations.
Common Arithmetic Operators:
+
** (Addition)\**:python >>> 40 + 2 42
-
** (Subtraction)\**:python >>> 43 - 1 42
*
** (Multiplication)\**:python >>> 6 * 7 42
/
** (Division)\**:python >>> 84 / 2 42.0
**
** (Exponentiation)\**:python >>> 6**2 + 6 42
**The *
^
* Operator*: In Python,^
is a bitwise operator known as *XOR**, not exponentiation (which uses**
). Using it for exponentiation will produce unexpected results if you are unfamiliar with bitwise operations.python >>> 6 ^ 2 4
Bitwise operators are not covered in this course.
Values & Types
Value: One of the fundamental pieces of data that a program works with, such as a letter or a number. Examples include 2, 42.0, and
'Hello, World!'
.Type: A category that classifies values.
int
** (integer)\**:float
** (floating-point number)\**:str
** (string)\**:
Determining a Value's Type: The
type()
function can be used to find out the type of a value.python >>> type(2) <class 'int'> >>> type(42.0) <class 'float'> >>> type('Hello, World!') <class 'str'>
The word "class" here refers to a category, indicating that a type is a category of values.
Quoted Numbers: Values enclosed in quotation marks, such as
'2'
or'42.0'
, are considered strings (str
) even if they look like numbers.python >>> type('2') <class 'str'> >>> type('42.0') <class 'str'>
Commas in Large Numbers: Commas cannot be used as digit separators in Python integers.
1,000,000
is not interpreted as one million. Instead, Python interprets it as a comma-separated sequence of integers, resulting in a tuple(1, 0, 0)
.
Formal & Natural Languages
Natural Languages: Languages that humans speak, such as English, Spanish, or French. They evolved naturally without deliberate design.
Formal Languages: Languages specifically designed by people for particular applications.
Examples: Mathematical notation (denotes relationships among numbers/symbols), chemical notation (represents molecular structures).
Programming Languages: A crucial category of formal languages, designed to express computations.
Syntax Rules: Formal languages adhere to strict syntax rules governing statement structure.
Tokens: The basic elements of the language (e.g., words, numbers, chemical elements).
Example: In math,
3 + 3 = 6
has correct syntax, but3+ = 3$6
has an illegal token ($
). In chemistry,H2O
is correct, but2Zz
is not (Zz
is not an element symbol).
Structure: How tokens are combined.
Example:
3+ = 3
is illegal because an operator (=
) cannot immediately follow another operator (+
). In chemistry, subscripts come after the element name.
Parsing: The process of analyzing a sentence or statement to determine its structural meaning. In natural languages, this happens subconsciously.
Key Differences between Formal and Natural Languages:
Ambiguity:
Natural: Highly ambiguous; humans rely on context and other information to disambiguate.
Formal: Designed to be unambiguous, meaning each statement has one precise meaning, regardless of context.
Redundancy:
Natural: Often verbose, employs significant redundancy to overcome ambiguity and reduce misunderstandings.
Formal: Less redundant and generally more concise.
Literalness:
Natural: Rich in idioms and metaphors (e.g., "The penny dropped" implies understanding, not a literal coin).
Formal: Interpret everything exactly as stated, literally.
Analogies for understanding: The difference is more pronounced than between poetry and prose.
Poetry: Uses words for sound and meaning; the whole poem creates an effect; ambiguity is common and often deliberate.
Prose: Literal meaning of words is paramount; structure contributes meaning; more amenable to analysis but still often ambiguous.
Programs: Meaning is unambiguous and literal; can be understood entirely by analyzing tokens and structure.
Challenges of Formal Languages: They are denser, require more careful reading, and their structure is critical (not always read left-to-right). Attention to detail is paramount; minor spelling or punctuation errors can have significant consequences.
Assignment Statements
Variable: A name that serves as a reference to a value.
Assignment Statement: A statement that creates a new variable and links it to a specific value.
python >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.141592653589793
In the example,
message
is assigned a string,n
an integer (17), andpi
a floating-point number (3.141592653589793).
State Diagram: A common visual representation for variables, where the variable name points with an arrow to the value it refers to. This illustrates the "state" or current values of the variables.
Example Representation:
message --> 'And now for something completely different'
n --> 17
pi --> 3.141592653589793
Variable Names
Meaningfulness: Programmers typically choose variable names that clearly describe their purpose, acting as self-documentation.
Naming Rules:
Can be of any length.
Can include both letters (uppercase
A-Z
, lowercasea-z
) and numbers (0-9
).Cannot begin with a number.
Convention: While uppercase letters are legal, it is conventional practice in Python to use only lowercase letters for variable names.
*Underscore *
_
: Can be used within a name, often to make multi-word names more readable (e.g.,your_name
,airspeed_of_unladen_swallow
).
Illegal Variable Names: Attempting to use an illegal name results in a
SyntaxError
.76trombones = 'big parade'
is illegal because it begins with the number 76.more@ = 1000000
is illegal due to the invalid character@
.class = 'Advanced Theoretical Zymurgy'
is illegal becauseclass
is a Python keyword.
Keywords: Words reserved by the Python interpreter to understand the program's structure. They cannot be used as variable names.
Python 3 Keywords:
False
,None
,True
,and
,as
,assert
,break
,class
,continue
,def
,del
,elif
,else
,except
,finally
,for
,from
,global
,if
,import
,in
,is
,lambda
,nonlocal
,not
,or
,pass
,raise
,return
,try
,while
,with
,yield
.In most development environments, keywords are highlighted (e.g., in a different color like purple in Notepad++) to help programmers avoid using them as variable names.
Expressions & Statements
Expression: A combination of values, variables, and operators that the Python interpreter evaluates to produce a single result.
A single value (e.g.,
42
) is an expression.A single variable (e.g.,
n
) is an expression.Combinations like
n + 25
are expressions.When an expression is typed at the interactive prompt, the interpreter evaluates it and displays its value.
python >>> 42 42 >>> n # assuming n has been assigned a value, e.g., 17 17 >>> n + 25 # assuming n is 17 42
Statement: A unit of code that performs an action or has an effect, rather than producing a value.
Examples: An assignment statement (e.g.,
n = 17
) creates a variable; aprint
statement (e.g.,print(n)
) displays a value.When a statement is typed, the interpreter executes it, meaning it performs the action the statement specifies.
Statements generally do not have values themselves.
Script Mode
Interactive Mode: A direct way to interact with the Python interpreter by typing commands line-by-line. Useful for quick tests and exploration.
Script Mode: An alternative to interactive mode for larger programs. Code is saved in a file (a script), and the interpreter is run on this file to execute the code.
File Naming Convention: Python scripts typically have names ending with the
.py
extension.Running a Script: Instructions for creating and running scripts are usually found in supplementary materials (e.g., "Using Spyder" file).
Differences in Expression Handling (Interactive vs. Script Mode):
Interactive Mode: When an expression is entered at the prompt, the interpreter automatically evaluates it and displays its result.
python >>> miles = 26.2 >>> miles * 1.61 42.182
Script Mode: In a script, an expression on its own has no visible effect. Python evaluates it internally, but the result is not displayed to the user unless explicitly requested with a
print
statement.python # In a script file (.py) miles = 26.2 miles * 1.61 # This line produces no output in script mode print(miles * 1.61) # This line will print the result
Script Execution Flow: A script consists of a sequence of statements. The results of the statements (especially
print
statements) appear one after another as the script executes.python # Example script print(1) # Output: 1 x = 2 # This assignment statement produces no output print(x) # Output: 2
Order of Operations (PEMDAS)
Rule: When an expression contains multiple operators, the execution order is determined by operator precedence, following mathematical conventions.
PEMDAS Acronym: A mnemonic to remember the order of operations:
P - Parentheses
()
: Have the highest precedence. Expressions inside parentheses are evaluated first. They can be used to force a specific order of evaluation or to improve readability, even if they don't change the result.Example:
2 * (3-1) = 4
Example:
(1+1)**(5-2) = 8
Example for readability:
(minute * 100) / 60
.
E - Exponentiation
**
: Has the next highest precedence.Example:
1 + 2**3 = 9
(not(1+2)**3 = 27
)Example:
2 * 3**2 = 18
(not(2*3)**2 = 36
)
MD - Multiplication
*
and Division/
: Have higher precedence than addition and subtraction. They are evaluated from left to right if they appear together.Example:
2*3-1 = 5
(not2*(3-1) = 4
)Example:
6+4/2 = 8
(not(6+4)/2 = 5
)
AS - Addition
+
and Subtraction-
: Have the lowest precedence among these. They are evaluated from left to right if they appear together.
Left-to-Right Evaluation: Operators with the same precedence (except exponentiation) are evaluated from left to right.
Example: In
degrees / 2 * pi
(referring to(degrees / 2) * pi
), the divisiondegrees / 2
occurs first, and then the result is multiplied bypi
.To divide
degrees
by2 * pi
(i.e.,degrees / (2 * pi)
), you could writedegrees / 2 / pi
or, for better clarity,degrees / (2 * pi)
using parentheses.
Best Practice: Avoid relying solely on memory for operator precedence. Use parentheses generously to make the order of operations explicit and improve code readability.
String Operations
General Rule: Mathematical operations (like subtraction, true division) cannot typically be performed on strings, even if the strings contain numeric characters.
Illegal Examples:
'2'-'1'
,'eggs'/'easy'
,'third'*'a charm'
.
Exceptions (
+
** and*
)\**:+
** (String Concatenation)\**:python >>> first = 'throat' >>> second = 'warbler' >>> first + second 'throatwarbler'
*
** (String Repetition)\**:python >>> 'Spam' * 3 'SpamSpamSpam'
Analogy: The behavior of
+
and*
for strings can be understood by analogy with integer addition and multiplication. For instance,'Spam'*3
is equivalent to'Spam'+'Spam'+'Spam'
.Key Distinction: String concatenation and repetition behave differently from integer operations in significant ways (e.g., string concatenation is not commutative;
'a' + 'b'
is not the same as'b' + 'a'
).
Comments
Purpose: As programs become larger and more complex, they become harder to read. Comments are notes written in natural language within the code to explain what the program is doing and why. They make the code more understandable for other programmers or future self.
Syntax: Comments begin with the
#
symbol. Everything from#
to the end of that line is ignored by the Python interpreter and has no effect on the program's execution.Placement:
On a standalone line:
python # compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60
At the end of a line: As long as it doesn't make the line excessively long.
python percentage = (minute * 100) / 60 # percentage of an hour
Usefulness: Comments are most valuable when they document non-obvious aspects of the code or explain the reasoning behind a particular implementation, rather than simply restating what the code does (which should ideally be clear from the code itself).
Redundant/Useless Example:
v = 5 # assign 5 to v
Useful Example:
v = 5 # velocity in meters/second.
(This adds crucial information not evident from the code alone).
Trade-off with Variable Names: While good, descriptive variable names can reduce the need for comments, very long names can sometimes make complex expressions difficult to read, thus requiring a balance.
Debugging
Definition: Programming errors are whimsically called bugs, and the systematic process of finding and fixing them is called debugging.
Emotional Aspect: Debugging can often trigger strong emotions such as anger, despondency, or embarrassment due to a natural human tendency to react to computers as if they were people.
Coping Strategy: It's helpful to view the computer as an employee with specific strengths (speed, precision) and weaknesses (lack of empathy, inability to grasp context). Your role as a "manager" is to leverage its strengths and mitigate its weaknesses, channeling your emotions constructively.
Developing Debugging Skills: This is a valuable skill applicable beyond programming.
Recommendation: Actively experiment with making mistakes when learning new features (e.g., omitting quotation marks or misspelling
print
). This helps in understanding error messages better and building practical debugging intuition.
Three Kinds of Errors in Programs:
Syntax Error:
Definition: Errors related to the structure and grammatical rules of the programming language.
Examples: Unmatched parentheses (e.g.,
8)
), using an illegal variable name (e.g., starting with a number like76trombones
, or containing an illegal character likemore@
, or using a keyword likeclass
).Effect: Python displays an error message and immediately quits; the program cannot be parsed or run.
Frequency: Very common for new programmers, but proficiency reduces their occurrence and detection time.
Runtime Error (Exception):
Definition: Errors that emerge only after the program has started executing. They are called exceptions because they typically signal an unusual and problematic event during runtime.
Frequency: Generally rare in simple programs but become more prevalent in more complex applications.
Semantic Error:
Definition: Errors concerning the meaning or intended logic of the program. The program runs successfully without throwing any error messages.
Effect: The program executes what it was told to do, but this is not what the programmer intended it to do, leading to incorrect or unexpected results.
Identification: These are often the trickiest to find because there are no explicit error messages. Debugging semantic errors requires working backward from the incorrect output to deduce the logical flaw in the code.
Lesson Review Exercises
The lesson concludes with exercises (1.1, 1.2, 1.3, 1.4) designed to test and reinforce understanding of the concepts covered, including using the Python interpreter as a calculator, building debugging skills by purposely introducing errors, and practicing new features.
Glossary of Terms
Assignment: A statement that assigns a value to a variable.
Bug: An error in a program.
Comment: Informational text within a program, intended for human readers, that has no effect on the program's execution.
Concatenate: To join two operands (like strings) end-to-end.
Debugging: The systematic process of finding and rectifying bugs in a program.
Evaluate: To simplify an expression by performing its operations to yield a single resultant value.
Exception: An error detected while a program is actively running; synonymous with a runtime error.
Execute: To run a statement and perform the action it specifies.
Expression: A combination of variables, operators, and values that, when evaluated, represents a single result.
Floating-point: A data type (
float
) used to represent numbers that include fractional parts.Formal language: Any language designed by humans for specialized applications, such as mathematical notation or programming languages. All programming languages fall into this category.
High-level language: A programming language (e.g., Python) designed to be user-friendly for humans to read and write.
Integer: A data type (
int
) used to represent whole numbers.Interactive mode: A method of using the Python interpreter by directly typing code commands at a prompt and receiving immediate feedback.
Interpreter: A program that reads and executes instructions written in another program.
Keyword: A reserved word in a programming language that holds special meaning for the interpreter and cannot be used as a variable name.
Low-level language: A programming language designed for a computer to execute directly, often referred to as "machine language" or "assembly language".
Natural language: Any human language that has evolved naturally over time, such as English or Spanish.
Operand: One of the values upon which an operator performs its operation.
Operator: A special symbol that signifies a simple computation, such as addition, multiplication, or string concatenation.
Order of operations: A set of rules that dictate the sequence in which operations within an expression containing multiple operators and operands are evaluated.
Parse: To examine and analyze the syntactic structure of a program or statement.
Portability: A characteristic of a program that allows it to run on various types of computer systems without significant modification.
Print statement: An instruction that directs the Python interpreter to display a specified value on the screen.
Problem solving: The comprehensive process of articulating a problem, devising a solution, and expressing that solution clearly and accurately.
Program: A predefined set of instructions that specifies how to perform a computation.
Prompt: Characters displayed by the interpreter (e.g.,
>>>
) to indicate its readiness to receive user input.Script: A program stored in a file.
Script mode: A method of using the Python interpreter to read and execute code from a saved script file.
Semantic error: A logical error in a program where the code executes successfully but produces an outcome different from the programmer's intention.
Semantics: The inherent meaning or logic of a program.
String: A data type (
str
) that represents sequences of characters.State diagram: A visual representation showing the current values assigned to a set of variables.
Statement: A segment of code that represents a command or action (e.g., assignment statements, print statements).
Syntax: The rules that govern the correct structural formation of a program.
Syntax error: An error in the structure or grammar of a program that prevents it from being parsed and interpreted.
Token: A basic, irreducible element of a program's syntactic structure, analogous to a word in natural language.
Type: A category that classifies values (e.g.,
int
,float
,str
).Value: One of the fundamental units of data, such as a number or