Computer Programming Notes
Why Program Computers
Computers are built to help and perform tasks for us.
We need to communicate with them in their language.
Users interact with programs by selecting options.
Programs answer questions and guide the computer.
Programmers anticipate user needs and create tools.
Programming allows building tools for a wide audience.
Examples:
Cleaning up survey data.
Fixing performance issues.
Adding guestbooks to websites.
Programs for Myself vs. Others
Writing programs for personal use differs from professional programming.
Professionals require more engineering and rigor.
Programmers write code for data information networks used by others.
They solve problems for users using hardware and software.
Programs
Program: A sequence of stored instructions.
Computers have flexibility; programs dictate their actions.
Programs must be perfect for computers.
Syntax Errors: Occur when a computer detects imperfections in the code, leading to confusion and inaction.
Text Analysis Using Python
Python is useful for text analysis.
Example: Counting word occurrences in a text.
Hardware Overview
Input/Output Devices: Enable computer interaction (e.g., mouse, keyboard, screen).
Central Processing Unit (CPU): Executes instructions.
A sophisticated circuit with transistors.
Runs instructions as electrical pulses.
Executes billions of instructions per second.
Main Memory: Answers CPU's questions about what to do next.
CPU
CPU transistors store yes/no questions and information.
All parts are connected via the motherboard.
Memory
Main Memory:
Fast, small, temporary storage.
Erased when the computer turns off.
Secondary Storage:
Slower, larger, permanent storage.
Retains data until deletion (e.g., disc drive, memory stick).
Definitions
CPU: Runs programs, constantly asking "what's next?"
Input Devices: Keyboard, mouse, touchscreen.
Output Devices: Screens, speakers, printer.
Main Memory (RAM): Fast, small, temporary storage; loses data upon restart.
Secondary Memory: Slower, large, permanent storage.
Program Execution
Instructions are fed to the CPU in machine language (zeros and ones).
Execution follows a Fetch-Execute cycle.
Translation from Python file to Main Memory is done by a compiler/interpreter.
Python
Using Python Playground for coding.
Chevron Prompt: Beginning of Python code.
Python Elements
Assignment Statement: Stores information with a label.
Example: (assigns 1 to the label x).
Print: Retrieves information labeled as x.
Example:
print(x).
SyntaxError: Occurs if there's something wrong in the code.
Python
Elements of Python:
Vocab words, variables, reserved words.
Sentence structure and valid syntax patterns.
Program structure for a purpose.
Each level builds upon the previous one.
Python
Eventual Program Written Context: Python story about counting words in a file.
Reserved words: Words used exactly as Python expects them (e.g.,
def,if,while).
Sentences/Lines
Sentences are lines in Python.
Assignment statement: Assigns a value to a variable (e.g., ).
Assignment with expression: Assigns the result of an expression to a variable (e.g., ).
Print function: Displays a value (e.g.,
print(x)).Variable: A named storage location.
Operator: A symbol that performs an operation (e.g., +, -, *).
Constant: A fixed value (e.g., 2, 4).
Function: A reusable block of code.
Python Scripts
Interactive Python: Suitable for experiments and short programs (3-4 lines).
Python Scripts: Used for longer programs, stored in files with a
.pysuffix.
Program Steps
Scripts are series of steps with patterns:
Sequential: Steps execute in order.
Conditional: Steps are skipped based on a condition (e.g.,
if x is true, do y).Repeated: Instructions are repeated (e.g., loops).
Conditional Steps
ifstatement: Ignores code if the condition is not applicable.whilestatement: Continues until the condition is not applicable, creating a loop.
Code Examples
Reading a file and counting word frequency:
name = input('Enter file: ')
handle = open(name)
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
Chapter 2
Expressions and Variables
Constants:
Fixed numbers, letters, strings.
String constants use single or double quotes.
Variables:
Reserved words that shouldn't be used for other purposes.
Places where Python allocates memory to store values.
Naming Rules
Start variables with letters or underscores (avoid underscores).
Consist of letters, numbers, and underscores.
Case-sensitive.
Sentences/Lines
Use MNEMONIC names for variables (sensible and understandable).
Mnemonic variables are for humans.
Assignment Statements
Assign a value using the = operator (e.g., ).
Operators
Based on keyboards from the 1960s.
Numeric Expressions
Operators:
Addition: +
Subtraction: -
Multiplication: *
Division: /
Power: **
Remainder: %
Order of Evaluation
Python follows operator precedence rules (PEMDAS/BODMAS).
Parentheses
Exponentiation
Multiplication, Division, Remainder
Addition and Subtraction
Left to right
Operator Precedence Rules
Type
Variables, literals, and constants have a "type".
String and Integers
Python distinguishes between integers and strings.
+means addition for numbers and concatenation for strings.
Ex:
ddd = 1 + 4
print(ddd) #Output: 5
eee = 'hello ' + 'there'
print(eee) # Output: Hello There
Types can be:
Integers: Variables or constants without decimal places.
Floating-point numbers: Constants with decimal places (more range but less precision).
Type Conversions
Use
float()to convert to floating-point.Integer division in Python 2 truncates decimal places.
String Conversions
Strings with no digits cannot be converted to integers.
Input
Use
input()to get data from the outside world.Very sensitive, includes spaces, etc.
Comments
Important for making programs understandable.
Python ignores comments.
Use the
#sign to turn off lines of code.
Example
# convert to fahrenheit
celsius = input("Enter Celsius Temperature:")
fahr = float(celsius) * 1.8 + 32.0
print(fahr)
Chapter 3
Conditional Statements
Boolean Expressions
Ask a question and produce a Yes or No (True/False) result.
Comparison Operators
Look at variables but do not change them.
Less than: <
Less than or Equal to: <=
Equal to: ==
Greater than or Equal to: >=
Greater than: >
Not equal: !=
One-Way Decisions
x = 5
if x == 5:
print('Equals 5')
if x > 4:
print('Greater than 4')
if x >= 5:
print('Greater than or Equals 5')
if x < 6:
print('Less than 6')
if x <= 5:
print('Less than or Equals 5')
if x != 6:
print('Not equal 6')
Nested Decisions
x = 42
if x > 1:
print('More than one')
if x < 100:
print('Less than 100')
print('All done')
Two-way Decisions
Use
ifandelse.
x = 4
if x > 2:
print('Bigger')
else:
print('Not bigger')
print('All Done')
Visualize Blocks
Multi-way If
Uses
elif(else if).
if x < 2:
print('small')
elif x < 10:
print('Medium')
else:
print('LARGE')
print('All done')
No Else Multi-way
if x < 2:
print('Small')
elif x < 10:
print('Medium')
Try Except Structure
Used to catch and handle tracebacks (errors).
Prevents the program from crashing.
astr = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1
print('First', istr) # Output: First -1
Sample try / except
rawstr = input('Enter a number:')
try:
ival = int(rawstr)
except:
ival = -1
if ival > 0:
print('Nice work')
else:
print('Not a number')
Chapter 4
Functions
Stored (and reused) Steps
Functions store and remember steps for later use.
def thing():
print('Hello')
print('Fun')
thing()
thing()
print('Zip')
# Output:
# Hello
# Fun
# Hello
# Fun
# Zip
Function
A variable that holds code.
Call/invoke a function to execute the code it holds.
When Python calls a function, it remembers where to return.
Naming functions: same rules as for variables (avoid reserved words).
defkeyword defines a function.Call/invoke: use function name with parentheses.
Max Function
big = max('Hello world')
print(big) # Output: w
Type Conversions
Use
int()andfloat()to convert between strings and integers.input()always returns a string.
sval = '123'
print(type(sval)) # Output: <class 'str'>
ival = int(sval)
print(type(ival)) # Output: <class 'int'>
print(ival + 1) # Output: 124
Building Own Functions
defkeyword followed by optional parameters.Indent the body of the function.
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
Arguments
A value passed into the function as its input.
Arguments allow functions to do different tasks based on the input.
```python
big = max('Hello world') #