Introduction to Python
Joel Ross
Spring 2019
IMT/LIS 511
Any questions on the homework?
Today's Objectives
By the end of class, you should be able to
- Feel confident with version control basics.
- Understand how to to write, execute, and debug computer programs in the Python language
- launch and interact with Jupyter Notebooks
- launch and interact with Jupyter Notebooks
- Store data in variables
- Utilize functions to manipulate data (if time)
Using GitHub (Forking)
edit files
staging area
git add
git commit
exercise repo
your copy
git clone
your machine
fork
git push
git pull
Warmup: Git
-
Fork and clone
ch4-python-intro to your computer (pick a general directory where you'll keep all your class work:
Desktop
,Documents
,~
(Home), etc).
- Change directory into the exercise repo
- Create a file
STUDENT.md
that contains your name:
Challenge: do this with the command line! (useecho
and redirects>>
)
-
add
andcommit
your changes
-
push
your changes back to GitHub, and view the file on the website to confirm that everything worked!
# Student
These exercises were completed by YOUR NAME.
# IF YOU CLONE THE WRONG REPO: change the remote bookmark
git remote set-url origin https://github.com/USER_NAME/ch4-python-intro
A high-level, general purpose, interpreted programming language
-
High Level: closer to human language than machine language
-
General Purpose: can be used for multiple domains
-
Interpreted: Python language is translated into machine language as it is being run (vs. compiled language)
Python Versions
Python originally released in 1991
Python 2 released in 2000 (now EOL)
Python 3 released in 2008
Python 2 and Python 3 are not compatible!
what we're using
Jupyter Notebooks
Jupyter Notebooks are interactive web applications that can be used to write and execute Python programs (as well as textual content). Notebooks can also be shared with others!
Using Jupyter
Start the Jupyter Notebook server (command line)
jupyter notebook
Create a new notebook or open an existing one (.ipynb
)
Type your code into a code cell.
-
shift + enter
to execute a cell (or use the Cell menu)
You can add additional cells, including Markdown cells.
- See the command palette for more options
You can "restart" the interpreter through the Kernel menu.
Python Code
# My first program
print("Hello world!")
Printing
Use
print()
to print whatever is in the parentheses to the console. This is an example of a
function.
What could go wrong?
# My first program
print "Hello world!"
# My first program
print("Hello world!)
# My first program
print("Hello wold!")
Python 2 syntax!
Computer Bugs
First computer bug (1946)
Admiral Grace Hopper
Types of Bugs
Syntax Error
Logical Error
Semantic Error
- An error in the use of the Python language. A problem with how you said something.
- Interpreter will error at the site of the problem.
- An error in your approach to solve a problem.
- Interpreter will not error, but will not do what you want.
- An error in the algorithm you used. A problem with what you said to do.
- Interpreter will error, but possibly after the problem.
Some Debugging Tips
-
Read the error message!
-
"Play Computer" (how is it interpreting your code?)
-
Inspect the data (e.g., print it!)
-
Try one statement at a time (isolate the problem)
-
Explain your code to someone else ("rubber duck debugging")
-
Ask for help when stuck!
Debugging is what programming is all about
num_cups_coffee = 3
Variables
A label that refers to a value (of data)
Using Variables
Once we have a variable, we can use that label to refer to a value (in place of a value)
x = 4 # x refers to 4
y = x # y refers to the value of x (4)
z = y + 7 # y refers to sum of y and 4 (11)
z = z + 1 # take z, add 1, and store result
# back in z
When a label is on the left, it means the variable.
When a label is on the right, it means the value.
Assignment is
not Equality!
Assignment gives a label to a value. Changing which value a variable refers to doesn't change other variables.
x = 3
y = 4
x = y # assign the value of y (4) to x
print(x) # 4
y = 5
print(x) # 4;
Good variable names describe the data
# valid program, but what does it mean?
a = 35.0
b = 12.50
c = a * b
# much better!
hours = 35.0
pay_rate = 12.50 # needs a raise!
earnings = hours * pay_rate
# Get out.
x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
Data Types
Variable Types
All values in Python have a particular data type or class ("classification"). Class determines how that data can be used.
type(7) # <class 'int'> (integer)
type(3.14) # <class 'float'> (decimal)
type("Hello") # <class 'str'> (string, text)
Python is dynamically typed, so variables (labels) can refer to any type of value.
my_var = "Hello" # value is a string
my_var = 42 # value is now an integer
Numbers
Integers (whole numbers) and floats (decimals) are used to store numbers.
x = 2 # whole number
y = 3.5 # decimal (floating point) number
# can perform mathematical operations
z = x + y
# Use parentheses to enforce order of operations
z = 3*(x-y)**2
operator
operands
If an operand is a
float
or you use the division (/
) operator, the result will be a float.
Strings
Strings of characters (letters, punctuation, symbols, etc). Written in single or double quotes.
my_name = "Joel" # 'Joel' would be equivalent
# Can include any keyboard symbol (and more!)
course = "IMT/LIS 511: Intro to Programming!"
# Can concatenate strings together
greeting = "Hello" + " " + "World"
# Convert a number to a string to concatenate it
course_code = "IMT/LIS " + str(511)
Functions
f(x) = 4x - 3
function
name
input (domain)
result
(range)
Functions
A named sequence of instructions (lines of code). We call a function to do those steps.
Functions abstract computer programs!
print("Hello world")
function name
argument (value)
Functions
# prints "Hello+++World"
print("Hello", "World", sep = "+++")
multiple arguments are separated by commas
keyword argument
# rounds 5/7 to the nearest .01
round(5/7, 2) # 0.71
Argument order (position) usually matters
Function arguments are the "inputs".
expressions in args are evaluated before the function is executed
Functions
Functions may return a value (the "output"). This value must be stored in a variable for the machine to use later!
# store min value in smallest_number variable
smallest_number = min(1, 6/8, 4/3, 5+9) # 0.75
# use the variable as normal, such as for math
twice_min = smallest_number * 2 # 1.5
# use functions directly in expressions
# (the returned value is "anonymous")
number = .5 * round(9.8) # 5.0
# pass the result of a function as an arg to another!
# (`abs` is "absolute value")
# watch out for where the parentheses close!
print(min(2.0, abs(-3))) # prints 2.0
Object Methods
All data values in Python are objects, which include both data (attributes) and behaviors (methods, a.k.a functions)
We can call methods (functions) on a particular data value in order to apply that behavior to that value.
(e.g., tell a particular person variable to say_name()).
Text
Dot Notation
We call a method on a data value by using
dot notation, putting the data value, then a dot (
.
), then the function call.
message = "Hello World"
# call the lower() method on the message
# original string does not change
lower_message = message.lower() # "hello world"
# call the replace() method on the message
western_message = message.replace("Hello", "Howdy")
## "Howdy World"
The dot is like an
's in English: "execute message
's lower()
"
Built-in Functions
https://docs.python.org/3/library/functions.html
String Methods
https://docs.python.org/3/library/stdtypes.html#string-methods
Fork and clone
Open in Jupyter Notebook (command-line)
cd path/to/module/exercise
jupyter notebook exercise.ipynb
Action Items!
- Be comfortable with Chapters 1-4
- Assignment 1 due Wednesday
- Ask if you get stuck or have problems!
- Read Chapter 5 (required)
Next time: functions!
imtlis511s19-python-intro
By Joel Ross
imtlis511s19-python-intro
- 680