Notebook 1 - Course Overview, Background, and Getting Started¶
You can make your own copy of this notebook by selecting File->Save a copy in Drive from the menu bar above.
Things you'll learn in this lesson:
- An overview of this course
- A brief background on computing, programming, and Python
- Some getting start material
Course Overview¶
Course Description¶
Pylearn is...
- inclusive - no prerequisites, perfect for beginners
- approachable - nothing to install or configure
- convenient - learn at your pace, on your schedule
- free - no fees, no ads, not now, not ever
- practical - understand not only how, but why
- respectful - we never request or store any personal information
- interactive - learn by doing, using Colab notebooks
Course Goals¶
- Demystify programming in general and Python in particular
- Show how to use Python to a practical, hands-on way
- Provide a solid foundation for diving deeper
Target Audience¶
- Programming and/or Python beginners
- Underrepresented groups in tech
- Aspiring data scientists
There are no prerequisites for this course. We'll start at the beginning.
Syllabus¶
Lesson | Title |
---|---|
Notebook 1 | Course Overview, Background, and Getting Started |
Notebook 2 | Numbers, Strings, Variables, and Assignment Statements |
Notebook 3 | Boolean Comparisons, Boolean Operators, and Expressions |
Notebook 4 | Controlling Program Flow and Using Modules |
Notebook 5 | More Strings and Loops |
Notebook 6 | Functions, Namespaces, and Modules |
Notebook 7 | Tuples, Lists, and Dictionaries |
Notebook 8 | Files, Errors, and Exceptions |
Notebook 9 | Sample Project |
Some thoughts on learning to code¶
- Programming is a creative activity.
- There has never been a better time in history to learn to code.
- Anyone can learn to program, as long as you’re willing to do the work.
- Think of it a little like learning to play a musical instrument.
- Practice between classes is very helpful.
- Give yourself time & kindness.
- Mistakes are feedback.
- When you get stuck:
- Don’t beat yourself up.
- Take a break.
- Don’t be afraid to ask me or a peer for help.
- The dirty secret about professional programmers: No one knows everything - we all use Google, Stack Overflow, and other websites all the time.
What is a Notebook?¶
- You're looking at one. :)
- Notebooks are interactive documents where you can read instructions and try your own code experiments in one unified experience.
- The notebooks we're using are called Jupyter and the hosting service (the notebook provider) is called Google Colaboratory or just "Colab". This service makes it easy to use and share Python notebooks for free, much like Google Docs.
From the menu bar, select Tools->Command Palette to see a list of the commands you can execute inside a Colab notebook. Most of these commands are intuitively named. For example, to save your notebook in Google Drive, run "Save notebook" now from the command palette. You can find it quickly by typing "save" in the search box.
Don't worry if you're not sure what some of the commands in the command palette do. For now, I just want you to know about this resource.
Congratulations for making it this far! Your last assignment is to watch this short video and take a quick tour of Colab.
It's a good idea to save your work after a notebook session. You can use the command palette to do this, as you just did in the previous cell, but since this is a common function, you'll see an easier way to save your notebook via the File->Save menu item.
When you run a cell in a notebook, where does it actually run?¶
Background¶
The March of Progress¶
The cell phone in your pocket has more computing power than all of NASA back in 1969. They used it to put two astronauts on the moon. We use it to play Candy Crush. :)
Learning to program gives you the power to build amazing things with your computer.
What is an operating system?¶
A software layer that functions as the computer’s traffic cop.
Operating systems provide:
- core system services (e.g. processes/threads, memory management)
- abstraction of lower level services (e.g. reading a file, using the network)
- permissions and access control (e.g. login authentication, verifying a user is allowed to access a file)
- resource management (e.g. multiple programs sharing the CPU, multiple access to the same disk device)
Popular operating systems: Windows, Linux, Android, iOS, MacOS
What is an algorithm?¶
A step-by-step procedure for solving a problem or accomplishing some end, especially by a computer
Example Algorithm: Marc’s Scrambled Eggs Recipe
Ingredients:
- 2 eggs
- butter
Cooking steps:
- mix eggs in a bowl
- lightly coat a frying pan with gasoline
- heat pan to 4000 degrees
- stir eggs until firm
- pour mixed eggs into frying pan
Just like programs, recipes can have errors, or "bugs". Can you find three bugs in this recipe?
What is a program?¶
- Encoding of an algorithm, in some particular programming language.
- In other words, a set of instructions, which tell a computer how to do something.
- Programming statements are called “source code” or just “code”.
- "Coding" is just another word for programming.
What is a programming language?¶
- A set of rules for expressing algorithms symbolically.
- Provides an abstraction layer for using your computer to solve a problem.
- Provides a way to reuse other peoples’ work.
Compiled vs. interpreted languages¶
[Source](https://medium.com/from-the-scratch/stop-it-there-are-no-compiled-and-interpreted-languages-512f84756664)- A compiler converts one language to another (usually a high level language to low level code that can be run directly by the hardware).
- An interpreter executes the source program one statement at a time.
- Portability vs. performance
What is Python and why learn it?¶
- an interpreted programming language that was invented in 1989 by Dutch programmer Guido van Rossum
- powerful and expressive
- easy to learn
- highly readable
- freely available open source
- widely used & well supported
- Very strong for:
- AI
- Data Science
- Finance
- Statistics
- Machine Learning
- Social Sciences
- Web development
- Education
- not a bad thing to have on your resume/CV
The Zen of Python¶
import this
Getting Started¶
Running a Python program from the command line¶
Example Programs¶
Example 1 - Print a Multiplication Table¶
for i in range(1,10):
print(i, end=' ')
for j in range(2, 10):
print(f'{i*j:2}', end=' ')
print()
Example 2 - Search IMDb¶
!pip install -q imdbpy
from imdb import IMDb
from IPython.display import Image
title = 'trainspotting'
imdb = IMDb() # create imdb API object
results = imdb.search_movie(title)
limit = 3
count = 0
for i in results:
if count > limit:
break
count += 1
if i.data[‘kind’] == ‘movie’:
movie = imdb.get_movie(i.movieID)
imdb.update(movie, info=[‘vote details’])
if ‘rating’ in movie.data:
display(Image(url=movie.data[‘cover url’]))
print(movie, movie.data[‘rating’])
Example 3 - Generate a Histogram¶
import seaborn as sns
countries = [‘UK’, ‘UK’, ‘India’, ‘UK’, ‘India’, ‘UK’, ‘Sweden’,
‘India’, ‘India’, ‘India’, ‘India’, ‘UK’, ‘India’, ‘Nigeria’,
‘US’, ‘Afghanistan’, ‘Afghanistan’, ‘US’, ‘UK’, ‘US’,
‘Afghanistan’, ‘UK’]
sns.countplot(countries)
Example 4 - Generative AI built into Colab¶
Try this in Colab:
# prompt: generate a colorful time series graph, make the values sparse, i.e. fewer than 20
import matplotlib.pyplot as plt
import numpy as np
import random
# Generate sparse time series data
num_points = random.randint(10, 19) # Ensure fewer than 20 data points
time_values = np.linspace(0, 10, num_points)
data_values = np.random.randint(1, 50, num_points)
# Create a colorful time series plot
plt.figure(figsize=(10, 6))
plt.plot(time_values, data_values, marker=‘o’, linestyle=’-’, color=‘blue’, linewidth=2)
plt.fill_between(time_values, data_values, color=‘skyblue’, alpha=0.4)
plt.xlabel(‘Time’)
plt.ylabel(‘Values’)
plt.title(‘Colorful Time Series Graph (Sparse Data)’)
# Add some aesthetics
plt.grid(True, linestyle=’–’, alpha=0.7)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
# Show the plot
plt.show()
Your first Python program¶
print('Hello world!')
Just for context, here's how we wrote that program in 1982:
HELLO CSECT The name of this program is 'HELLO'
* Register 15 points here on entry from OPSYS or caller.
STM 14,12,12(13) Save registers 14,15, and 0 thru 12 in caller's Save area
LR 12,15 Set up base register with program's entry point address
USING HELLO,12 Tell assembler which register we are using for pgm. base
LA 15,SAVE Now Point at our own save area
ST 15,8(13) Set forward chain
ST 13,4(15) Set back chain
LR 13,15 Set R13 to address of new save area
* -end of housekeeping (similar for most programs) -
WTO 'Hello World' Write To Operator (Operating System macro)
*
L 13,4(13) restore address to caller-provided save area
XC 8(4,13),8(13) Clear forward chain
LM 14,12,12(13) Restore registers as on entry
DROP 12 The opposite of 'USING'
SR 15,15 Set register 15 to 0 so that the return code (R15) is Zero
BR 14 Return to caller
*
SAVE DS 18F Define 18 fullwords to save calling program registers
END HELLO This is the end of the program
Now you see why I love Python. :)
The print
function provides a mechanism to generate output from a Python program. Another useful function to know about is the input
function. It's sort of the opposite of print
, because it gathers input into your program. Here's an example:
print('Enter your name: ')
name = input()
print('Hello', name + '!')
Printing a prompt before gathering input is such a common pattern that you can combine them into one function call, like this:
name = input('Enter your name: ')
print('Hello', name + '!')
🎉 Congratulations - you are now a Python programmer! 🎉
Errors - when bad things happen to good programs¶
"42" + "1"
Three kinds of errors¶
- syntax errors: invalid Python
print'Hello from Python')
- runtime errors: legal code tries to do something illegal
primt('Hello from Python')
print(10 / 0)
- logic errors: code is legal and runs fine but it does the wrong thing
age = birth_year - current_year
Comments¶
#
marks the rest of the line as a "comment"- Ignored by Python
- useful for documenting your code
- blank lines are also fine and sometimes improve readability
Example:
# Python ignores this line.
# print('this line does not print anything when commented out')
# The following blank lines are ignored as well...
#print(‘hi’) # this is a comment
# I can have as many comments and blank lines as I like in a program.
# They are for the benefit of me and “future me”.
Try removing the # preceding the print function call in the previous cell. We call this "uncommenting" a line of code.
Now put the # back in place. We call this "commenting out" a line of code. Often we'll do this to temporarily disable some code from running, where we want to keep the code in place for possible future use.
What is a function?¶
A reusable piece of code that completes a specific task.
We just met two functions - print
and input
are functions you used to do input/output (I/O) operations.
We say "call" or "invoke" a function to request that it do its job.
We do this by writing the function name followed by parentheses (aka brackets).
We may optionally include some values inside the brackets. We call those values function arguments, or just arguments.
We'll often refer to this process as "passing arguments" to a function.
I like to think of the function as a work request and the arguments as the job specification.
For example, you can pass arguments to the print function to produce just about any desired output.
print('test')
print()
print('this', 'is', 'a', 'test')
Built-in functions, like print
and input
are always available to use.
More about print¶
A print function call with no arguments simply prints a blank line:
print()
# Now try calling the print function with something else, like your name...
print('your name here')
Functions are the basic building blocks of a Python program. Later we'll see how to define your own functions. We've seen a simple print function call with zero and one argument:
print('My name is Marc')
We can also print a sequence of arguments, where spaces are added between each element in sequence, like this:
print('My', 'name', 'is', 'Marc')
print('next line')
By default, we get a newline character at the end of a print request but we can override that behavior using the end
argument:
print('My name is Marc')
print('next line')
print(‘My name is Marc’, end=’\n’)
print(‘next line’)
We can also change the separator string, using the sep
argument, like this:
print('My', 'name', 'is', 'Marc', sep='\n')
We could even use a null (empty) separator:
print('My', 'name', 'is', 'Marc', sep='', end='')
print('hi')
Useful Python Resources¶
Official Resources
Books and Articles
- A Whirlwind Tour of Python
- My Favorite Books for Beginning Python Students
- Spreading the Gospel of Python
- Why learn Python?
- codingbat.com
- CodeKata
Learning Resources
IDEs
Recommended Book for Further Study¶
Automate the Boring Stuff with Python
Great fit for our course:
- well written
- free to read online
- perfect for beginners
- focusses on practical applications
- if you buy it, make sure you get the 3rd edition
Documentation¶
- Official Python Documentation
- the
help
function (see example below) - Stack Overflow
- AI - I like Github Co-Pilot and Google Gemini
help(print)