Intro to Python

Learning Objectives
Students Will Be Able To: |
---|
Use the Python REPL |
Execute Python scripts |
Define and use variables |
Create comments |
Describe Python data types |
Use and format Strings |
Road Map
- Intro to the Python Language
- Using the Python Interpreter & REPL
- Python's Conventions, Variables, Data Types, etc.
- Essential Questions
- Further Study
1. - Intro to the Python Language
History
Back in December 1989 a Dutch programmer named Guido van Rossum was looking for a hobby project to keep himself occupied during his Christmas break.
The result was the very popular Python programming language!
Python was first released to the public in 1991.
Versions
Ten years after its release, Python 2.0 was introduced with many major new features and it started to gather a community dedicated to its development.
Python 3.0 was released in December 2008.
Version 3.0 introduced many enhancements, however, it included changes that made Python 3 incompatible with most existing version 2 applications.
Type of Language
Python, like JavaScript, is a high-level, object-oriented, interpreted programming language.
❗NOTE - It is necessary to note that many programming languages can be considered as interpreted/compiled/scripting languages, depending on their use. When we use JavaScript inside of our browser or when writing node.js, your script will be ran through an interpreter, making JavaScript behave as an interpreted language. But it is critical to remember: At its core JavaScript is a scripting language, even though in our current era of JavaScript development it is almost always used as an interpreted language.
As we'll explain below, an interpreted language is a language that has an interpreter translate the script provided by the engineer into an optimized version that can be better acted on by machines. It is also helpful to consider that it is assumed an interpreted language is going to hand its interpreted code off to a compiler to compile that middle-level interpreted code into machine code.
Due to the variety of language architectures and framework designs, as well as the inherent vagueness of the terms like 'interpreted' and 'compiled', it can often be confusing to determine exactly what any given programming language or framework is doing within your project without considering the exact application and architecture of your project. For the purposes of this course, we'd recommend to just consider Python and JavaScript as interpreted languages and consider the alternative varieties later on when you've developed a more mature understanding of how our programming systems behave and how they were designed.

High-level means that Python is designed for writing applications vs. lower-level software, such as operating systems and device drivers. It also means that programmers don't have to worry about things like memory management.
Also - like JavaScript - Python is a dynamic scripting language that does not have to be compiled before it can be executed. It runs within an interpreter that handles the conversion into machine code.
Python comes with a large standard library and is suitable for many types of programming tasks, from web development to machine learning and data science.
However, if Python does not include functionality that you need, there is a huge repository called the Python Package Index which has many third-party packages available for you to use.
Syntax & Semantics
Python was designed to be an easy-to-read programming language.
Its formatting is visually uncluttered and it often uses English keywords where other languages use punctuation or symbols. For example, the equivalent to JS's &&
operator in Python is and
.
Unlike many other languages, it does not use curly braces to define blocks of code, instead, it uses indentation.
2. - Using the Python Interpreter & REPL
We'll be using Python 3 at all times during SEI.
Ensure Python 3
is Installed
In terminal type: python3
If you receive an error, run brew install python
, quit and re-open terminal, and try python3
again.
Similar to what you saw with Node.js, Python comes with an interactive REPL (Read-Evaluate-Print-Loop) that provides a way to run Python code by typing in. For now, type exit()
or press control + d
to exit the REPL.
Running Python Scripts
In terminal, we can execute any Python script with this command:
python3 <filename>.py
Let's test this out by previewing a bit of Python by coding and running the infamous FizzBuzz function:
-
Move into your ~/code folder:
cd ~/code
-
Create a fizzbuzz.py script file:
touch fizzbuzz.py
-
Open fizzbuzz.py in VS Code:
code fizzbuzz.py
-
Code the
fizz_buzz()
function:fizzbuzz.py# Functions are defined using the def keyword
def fizz_buzz(max_num):
# Code blocks are defined using
# indentation after a :
'''
Loops through 1 up to max_num and prints message depending on evaluation of the integer
'''
for num in range(1, max_num):
if num % 3 == 0 and num % 5 == 0:
# Using string format method
print('{} is FizzBuzz'.format(num))
elif num % 3 == 0:
# Using newer f-string approach
print(f'{num} is Fizz')
elif num % 5 == 0:
print(f'{num} is Buzz')
else:
print(num)
fizz_buzz(31)
Now we can run the Python script as shown above by typing the following in terminal:
python3 fizzbuzz.py
As you can see, Python's print()
function outputs to the terminal.
Unlike with Node.js, providing the file extension (.py
) is required.
REPL
During the remainder of this lesson, we'll be experimenting inside of the Python interpreter/REPL.
In terminal: python3
At the >>>
prompt, type help()
, then type quit
to return to the REPL.
Cool, let's explore Python a bit in its REPL...
The Zen of Python
The Zen of Python is a simple import released with all versions of Python and added by Tim Peters. It shares with you 20 lines of text detailing the guiding principles of python. This is an easter egg of sorts, but can be insightful for better understanding why Python has been created in the way it has.
You can view these 20 guiding principles in the Python terminal by typing the following line of code into the terminal and hitting Enter:
import this
This will then print out the guiding principles like follows:
20 Guiding principles of Python:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
3. - Python's Conventions, Variables, Data Types, etc
Comments
We use the #
character to make a comment in Python:
# This is a comment! Python will ignore it.
Anything after the #
will not be run:
total_guitars = 7 # Hope someone knows how to play guitar
To make multiline comments, we use triple quotes """
or the #
on each line:
"""
This is a
multiline comment
"""
# This is a
# multiline comment
Multiline comments are often used to document what a function or module does, therefore they are sometimes referred to as docstrings.
Python Variables
Variables in Python work in much the same way that variables work in JavaScript.
Variables hold the data an app needs when it runs.
Declaring
Here is how we declare a variable in Python:
my_number = 15
Notice that there is no var
, let
, or const
keyword in Python. We only need the name of the variable and then we can assign a value to it.
However, you cannot just declare a variable without assigning a value to it - there is no undefined
in Python:
# illegal syntax...
my_variable
NameError: name 'my_variable' is not defined
Naming Convention
Variables are case sensitive - variables named my_number
and My_Number
would be two different variables.
When you have a variable name with multiple words, the convention is to snake_case the identifier:
// In JavaScript we use camelCasing...
var myNumber = 10;
# In Python we use snake_casing...
my_number = 10
Reassigning Variables
Just like in JavaScript, we can freely assign a new value to a variable after it is declared:
my_number = 15
print(my_number)
my_number = -4
print(my_number)
Of course, reassignment replaces the current value and that previous value would no longer be available - just like in JS.
👀 The
print()
function works very much likeconsole.log()
does in JavaScript.
Data Types
Python is a very object-oriented language.
In fact, pretty much everything in Python is an object that's been instantiated (created) by a particular class.
Checking the Data Type (class) of an Object
We use the type()
function to obtain the class used to instantiate the data:
>>> type(42)
<class 'int'>
>>> type('hello')
<class 'str'>
>>> type(True)
<class 'bool'>
Python's data types are similar to those available in JavaScript, there's just more of them...
Integer Numbers (<class 'int'>
)
Unlike in JavaScript, Python distinguishes between integers (whole numbers) and floats (numbers with decimals).
When we don't follow a number literal with a decimal point, an integer is assumed:
>>> some_int = 25
>>> type(some_int)
<class 'int'>
In JavaScript, we could use Math.floor()
to truncate the decimal portion of a number. In Python, we can convert non-integer numbers into integers using the int()
function:
>>> a_float = 1.7
>>> an_int = int(a_float)
>>> an_int
1
Floating-point Numbers (<class 'float'>
)
Numbers with a decimal point are stored in variables as floating-point numbers, usually just called a float
.
# Certain built-in features need to be imported
>>> import math
>>> pi = math.pi
>>> pi
3.141592653589793
>>> type(pi)
<class 'float'>
>>> some_float = 25.
>>> type(some_float)
<class 'float'>
Complex Numbers (<class 'complex'>
)
Python even has a data type for complex numbers, i.e., numbers with an "imaginary" component usually obtained by taking the square root of a negative number.
The imaginary portion is represented by the letter 'j':
>>> my_complex = 3+4j
>>> type(my_complex)
<class 'complex'>
Booleans (<class 'bool'>
)
Named after George Boole, these are the logical data types often used in conditional expressions.
Just like in JS, we have true
and false
except that their identifiers are capitalized:
>>> my_bool = True
>>> my_other_bool = False
>>> type(my_bool)
<class 'bool'>
You must start them with capital letters in Python or they will not reflect the boolean values.
Nothingness (<class 'NoneType'>
)
Python's equivalent to JS's null
& undefined
is None
:
>>> my_nothing = None
>>> type(my_nothing)
<class 'NoneType'>
The value None
in Python, with a capital N, provides the same meaning as null
does in JavaScript.
Math operations
Python has the normal math operators that you are used to from JavaScript:
- Addition
(+)
- Subtraction
(-)
- Multiplcation
(*)
- Division
(/)
- Modulo (remainder)
(%)
- Exponentiation
(**)
All work as you would expect. However, there few other things worth mentioning...
Integer Division
You can force the result to be an integer when dividing two integers using //
instead of /
:
>>> quotient = 5 // 2
>>> quotient
2
# 2 is printed, because the decimal ".5" is truncated
Shortcut Assignment Operators
As we saw in JS, the operation of reassigning value to a variable after it has undergone some type of math (addition, subtraction etc) is very common. Python has a number of shortcut operators that make that it a little cleaner to write than JS.
Python has the very same operators:
# This line of code...
num = num + 1
# ...can be written with this shortcut operator:
num += 1
# It also works for any of the other math operations:
num = num / 5
# Rewrite like this:
num /= 5
# And this...
num = num * 3
# Can be written as this...
num *= 3
# And so on with the other operators.
👀 A couple of our favorites in JS, the Increment (
++
) and Decrement (--
) operators, do not exist in Python. Use+= 1
and-= 1
instead.
Ternary Expressions
In JS we used the ternary expression to concisely return one of two values depending upon a conditional expression, for example:
// Using the ternary operator/expression
let beverage = age >= 21 ? 'Beer' : 'Milk';
// Without a ternary expression
let beverage;
if (age >= 21) {
beverage = 'Beer';
} else {
beverage = 'Milk';
}
However, Python does not have a dedicated ternary operator. Instead, it uses a modified syntax of if...else
which results in a ternary expression instead of a control flow construct.
The Python equivalence to the JS example above is:
beverage = 'Beer' if age >= 21 else 'Milk'
Converting Between Data Types
One thing we kind of took for granted in JavaScript was that it usually performed automatic datatype conversion for us - a process known as implicit type coercion
// JavaScript
let numTacos = 25;
let msg = 'There are ' + numTacos + ' tacos';
msg => There are 25 tacos
In the example above, 25 is a number that we can put inside of a string. However...in Python we cannot do this - there is no type coercion. Variables must be the same type to perform an operation on them (with just a few exceptions to that rule).
Luckily, doing math operations between integers and floats is allowed but not much else.
When the time comes to convert one data type into another, Python provides us with several global functions or predefined classes to do so:
str(item) # Converts item to a string
int(item, base) # Converts the provided item to an integer with the provided base
float(item) # Converts the item to a floating-point number
hex(int) # Converts an integer to a hexadecimal STRING
oct(int) # Converts an integer to an octal STRING
tuple(item) # Converts item to a tuple
list(item) # Converts item to a list
dict(item) # Converts item to a dictionary
Working with Strings
Python also has strings for holding text, just like JavaScript:
my_string = "A double quoted string"
your_string = 'A single quoted string'
You can also do some multi-line strings by using a triple quote (single or double):
multiline_string = '''This is my string that
goes on multiple lines
for whatever reason'''
Concatenating Strings
One or more strings can be combined into a single string in the same way we do it in JS: by using the +
operator:
little_string = "bad"
medium_string = "super"
long_string = medium_string + little_string
print(long_string)
# prints "superbad"
String Interpolation using f-Strings
Something that Python has had much longer than JavaScript is a nice syntax for performing string interpolation (i.e. evaluating Python expressions and embedding the result within strings).
While we can always use the concatenation operators above, these get ugly when too many of them appear in a string.
Instead, we can use a syntax similar to ES2015's template literals. You just need to remember to add an f
before the string:
state = "Hawaii"
year = 1959
message = f"{state} was the last state to join the U.S. in {year}."
When the f
is placed directly before the opening quote (single, or double) of the string, it makes a formatted string -- or f-String for short.
Once we do this, we can put expressions into curly braces to "inject" the result of the expressions into the string.
"f-Strings" are awesome, but they've only been available since version 3.6 (released in December of 2016). Prior to f-Strings, there were a couple of other options - one being the string format
method:
template = "My name is {} and I like {}"
print( template.format("Jim", "tacos") )
# prints 'My name is Jim and I like tacos'
Useful String Methods
Just like JS, Python has a number of string methods that we can use for string manipulation.
Some are familiar - like split()
- but others have different names:
"ace of spades".split(" ")
# => ['ace', 'of', 'spades']
# However, this won't work as desired
"abcd".split("")
# Instead, use the list() function like this:
list("abcd")
# => ['a', 'b', 'c', 'd']
# Warning: Raises error if substring not found
"tesla".index("s")
# => 2
# Like index, but returns -1 if substring not found
"tesla".find("x")
# => -1
"foo".upper()
# => "FOO"
"WHY???".lower()
# => "why???"
"Then I went to the store I like".replace("I", "you")
# => 'Then you went to the store you like'
Want to know if a string contains a substring?
You don't even need a function for that.... You can use the most excellent in
operator to quickly find out if one string appears in another:
"eggs" in "green eggs and ham"
# => True
Want to know the length of a string? Use the built-in global len()
function on a string to find its length:
len("Tacos")
# => 5
Python's Built-in Functions
Notice above that we did not call len()
as a method on the string - we didn't do this: "Tacos".len()
.
len()
is just one of several built-in functions that exists in Python.
len(arg)
- for example - is a function that returns the length (the number of items) of an object. The argument may be any sequence or collection (more on these soon).
Why does len()
work on strings? Because, in Python a string is a sequence of characters.
Because a string is a sequence
(as in JS), we can use square brackets to access the characters in that string:
course = 'SEI'
print( course[0] )
# => Prints 'S'
# We can use negative indexes!
last_letter = course[-1]
print( last_letter )
# => Prints 'I'
Later we'll see other fancy uses of square brackets.
Although we can access individual characters in a string, we cannot update the individual characters because strings are immutable (like in JS):
>>> s = 'Hello'
# I like Jello!
>>> s[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Let's wrap up with a few questions...
4. - ❓ Essential Questions (1 min)
(1) True or False: Every piece of data in Python is an object.
True
num = 25
msg = "There are " + num + " tacos"
(2) Will the above code run without error in Python?
No -- because Python doesn't convert the data types for us.
(3) String interpolation can be performed in Python by using __-Strings or a string's ________ method.
f-strings or a string's format()
method