Hey, Polyglots! Ready for another programming language?
- Know and use the basics of JavaScript
By the end of this, students should be able to:
- Compare and contrast basic language features and types from Python with basic language features and types from Javascript.
- Write and run simple script in Python.
- Install Python 3 - the most up to date version of Python.
brew install python3- Python doesn't ship with the most up to date version of package manager pip, so upgrade pip
pip3 install --user --upgrade pipPython is a high-level, general purpose programming language created by Guido van Rossum in 1991. It is the third most used programming language behind C and Java. Python can be used for data science, devops, or general purpose programming. In this class, we will be using it as a server-side "back-end" programming language.
Python has a couple attributes that make it unique:
- Meaningful Whitespace -- indentation signifies code blocks
- Duck typing -- the types of variables are inferred rather than explicitly declared
- Community -- there are so many Python libraries
- Easter Eggs -- Python is named after Monty Python, and there are a bunch of easter eggs built into the core language
Some easter eggs
Open the python3 shell with
python3and then type
import thisimport antigravityTim Peters, one of the original Python users wrote the following poem on the philosophy behind the Python language.
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!
- Snake Case:
keep_your_variables_defined_this_wayandwe_are_in_pythons_house_now. - Parens
()in Python are required around parameters at all times - Line breaks/ whitespace instead of semicolons, and closing curly braces!
- colons
:directly after the first line of the block statement, immediately followed by a new, indented line. Colons replace{in JS.
Similar to JS, but different.
>>> x = 2 # assigns x to numerical value 2
>>> x = "Take it easy dude. But take it!" # reassigns x to string valueBy default, variables are locally scoped. So name = "Origen" in Python is like let name = "Origen" in JS.
For constants, there is no way to make a variable specifically unable to be changed! But it is a widely practiced convention to declare constants in all caps:
NUMBER_OF_DAYS_IN_A_WEEK = 7
In Python, true and false are represented by True and False (yes, case
matters).
The falsy values of Python are:
False None 0 0.0 '' [] {}
None is equivalent to Javscripts's null.
Now that you know some more stuff, lets excecute code from a file!
🔵 Activity
In the file "main.py" (the white text editor on the lefthand side of the screen), do the following:
- Add some code using what you've learned so far!
- Run your code in the terminal using the "Run" button
- If you learn something, or something unexpected happens, share in a thread below
- 10 min
| JavaScript | Python | |
|---|---|---|
| logical operators | &&, ||, ! |
and, or, not |
| relational operators | == != > < >= <= |
== != > < >= <= |
| arithmetic operators | +, -, *, /, % |
+, -, *, /, //, % |
Integer division will always return a whole integer. Division with Floats returns most accurate results.
In Python, this whole integer division behavior can be mirrored with the //
operator.
>>> 14.5 / 3 # => 4.833333
>>> 14.5 // 3 # => 4.0Note that operations on floats will still return floats no matter the operator.
To convert between floats and integers, use:
>>> int(14.5) # => 14
>>> float(14) # => 14.0In Python, there is no difference between using " " or ' '.
Escape Characters
are evaluated in both.
>>> print("This is a \n new line.")
# => This is a
# => new line.There are many options for string interpolation in Python. For our
purposes, we'll be using .format(), as it is preferred for Python 3.5.
.format() is appended to a string and takes a parameters the strings to be
concatenated. If the string contains empty {}s, the parameters fill the {}s
in the order passed in. If they contain a number (beginning with 0), they will
be mapped to the parameter passed to .format() at said index.
>>> thing_to_do = "Take it"
>>> way_to_do_it = "easy"
>>> pronoun = "dude"
>>> "{} {} {}. But {}!".format(thing_to_do, way_to_do_it, pronoun, thing_to_do)
# => 'Take it easy dude. But Take it!'
>>> "{0} {1} {2}. But {0}!".format(thing_to_do, way_to_do_it, pronoun)
# => 'Take it easy dude. But Take it!'Another way introduced after Python 3.6 for string formatting is by using letter f,
>>> f'{thing_to_do} {way_to_do_it} {pronoun}. But {thing_to_do}!'
# => 'Take it easy dude. But Take it!'Again, colons and whitespace are critical to working Python code. Aside from
that and the use of elif vs. else if, these should feel very similar to Javascript conditional statements.
if x < 0:
print('Negative')
elif x == 0:
print('Zero')
else:
print('Positive')Also like Javascript, Python employs while and for loops.
Python also allows for an optional else statement with each of these. With
while loops, the else statement is executed once the while condition is
no longer true. With for loops, else is executed upon the loop's
completion.
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")count = 15
for i in range(1,count):
print(i)
else:
print("done")Again, this else is optional and different in nature from a conditional else.
It functions more as a completion handler.
Functions in Python are much like in JavaScript. For example, like in JavaScript, functions need a an explicit return.
Basic function structure:
def function_example(param_one, param_two):
"""Example function returning string interpolation of parameters."""
concat = "What a splendid function! I've got my {0} and {1}.".format(param_one, param_two)
return concatYou may have noticed something like
"""This function..."""
within each of our example functions. These are called docstrings and are
conventionally used in Python to provide documentation throughout a codebase.
Code will run fine without them, but that would stray from Python's conventions
as well as throw you into linter message hell. Try them out!
🔵 Activity FizzBuzz!
- create a new file "fizzbuzz"
- Add the code to solve FizzBuzz, explained below.
- You may have solved this in JavaScript or on a whiteboard before!
- If you learn something, or something unexpected happens, share in a thread below
- 10 min
Fizzbuzz is a classic, easy whiteboard problem in interviews. Remarkably, many hiring managers report that a majority of their applicants cannot solve it.
You write a function that will count from 1-99 printing 1 of four things for each number. If the number is divisible by 3, print "fizz". If the number is divisible by 5, print "buzz". If the number is divisible by 3 and 5, print "fizzbuzz". And otherwise, just print the number.
For the first 20 numbers, your console should look like this:
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzzPython lists are comparable to JavaScript arrays. They store comma separated values
of varying data types between square brackets [].
len() is used to get the length of a list in Python.
len(secret_files) # => 300We can merge lists together using the + operator:
secret_files = ["TOP SECRET", "ALSO TOP SECRET", "DON'T EVEN LOOK AT THIS"]
new_secret_files = ["PRETTY DARN SECRET", "WE SEEM NOT TO BE TRUSTED QUITE AS MUCH WITH TOP SECRET", "MAYBE IT'S THAT WE LEAVE SECRETS IN ALL CAPS IN PLAIN TEXT]
secret_files = secret_files + new_secret_files.append()instead of.push()
secret_files.append("He's guilty.").pop() removes the last element from a Python list.
We do not have built-in operators for removing or adding to the beginning of a list!
.remove(x) removes the first item from the list where list[i] is equal to x. Thus, list.remove("TOP SECRET")
would remove the first element from a list that matches "TOP SECRET".
for loops with lists don't stray far from the loops we saw earlier.
secret_files = ["TOP SECRET", "ALSO TOP SECRET", "DON'T EVEN LOOK AT THIS"]
for file in secret_files:
print(lang)-
Dictionaries are to Python as objects are to JS.
-
In computer science these types are also known as associative arrays or maps.
-
A dictionary provides a container for
key: valuepairs. We can refer tokey: valuepairs as items. -
Dictionaries have a class (type) of
dict.
-
Like objects in JS, a dictionary is created with a set of curly braces:
student = { 'name': 'Fred', 'course': 'WDI', 'current_week': 4 }
-
Unlike in JS, strings used as keys must be quoted.
Dictionaries have the following features:
-
They are unordered (just like JS objects)
-
They are mutable:
- The values assigned to a key can be changed
- New
key: valuepairs (items) can be added - Existing items can be deleted
-
Any immutable type can be used as a key, including numbers and tuples (which we'll cover in a bit).
-
We use square brackets to get and set an item's value:
name = student['name'] print(name) > Fred student['name'] = 'Tina' print(name) > Tina
-
Unlike with objects in JS, Python dictionaries have no dot notation.
-
Unlike JS which returns
undefinedwhen accessing a property that does not exist, a dictionary will raise aKeyError. -
One option to avoid this error is to use the
getmethod:birthdate = student['birthdate'] > KeyError: 'birthdate' print( student.get('birthdate', 'unknown') ) > unknown print( student.get('birthdate') ) > None
-
Another way to avoid the
KeyErroris to use theinoperator to check if the dictionary includes a key:import datetime if 'birthdate' in student: today = datetime.datetime.today() is_birthday = (student['birthdate'].month == today.month and student['birthdate'].day == today.day)
-
Simply assigning to a key that does not exist will create a new item in the dictionary:
student['age'] = 21
-
The
deloperator deletes an item from a dictionary:del student['age'] 'age' in student > False
-
Use the built-in
lenfunction to retrieve the number of items in a dictionary:print( student ) > {'name': 'Tina', 'course': 'WDI'} len(student) > 2 len({}) > 0
-
forloops are used to iterate over a dictionary'skey: valuepairs. However, the following is considered to be a Python anti-pattern:for key in student: print( f"{key} = {student[key]}" )
-
The preferred way is to use the
items()method to obtain a dictionary view object...
-
The best practice way to iterate over the items in a dictionary is to use a
forloop to iterate over a dictionary view object as follows:for key, val in student.items(): print( f"{key} = {val}" )
-
The
student.items()call above returns a wrapped set of tuples:student.items(): > dict_items([('name', 'Tina'), ('course', 'WDI')])
-
The
forstatement assigns the values in a tuple to multiple variables like withkey, valabove.
-
Define a Python dictionary named
where_are_my_thingscontaining a few items; where thekeysare things you have, and thevalueis the location you keep those things. -
Write a
forloop that iterates over the items in the dictionary and prints each one as My [thing] is kept [location].