
My name is Mattan Griffel, and I'm going to be your instructor. Who am I? I'm a co-founder of One Month and an adjunct professor at Columbia University Business School where I teach Python to MBAs. In this first lesson, I'll set expectations for the course, as well as answer the question: Can you really learn Python in just a month? Let's get started!
Welcome to class!
Welcome to Learn Python! I'm really excited to have you as a student, and I hope you're excited to learn some pretty cool stuff over the next month. By the end, if you stick along with it and do the work, I promise you'll have a deeper understanding of how to code with Python and the skills to build Python applications, start a new job in development, or get that promotion you've been dreaming of! I'll see you in the next lesson. — Mattan Griffel
Python is a general-purpose programming language that has wide application in various fields. In this lesson, we look at some areas in which Python is used, for example in web development, desktop app development, data science, building Internet of Things, creating distributed systems, etc. What can you do with Python? There are many, many cool things! We take a look, as well as cover what you will learn in this course.
What can you do with Python?
Python allows you to:
Automate repetitive tasks
Scrape data from websites like Google and Amazon
Interact with servers and APIs like Facebook, Twilio, Weather Forecasts, and Twitter
Perform data analysis
What famous companies use Python?
Python is used by companies like Dropbox, Google, Pinterest, The Washington Post, Firefox, and Instagram. It is HUGE, and yet you only need to know a fraction of the Python language in order to build very compelling apps. Many experienced developers have only barely scratched the surface. In this course, we'll focus on the most important parts of the Python language so that you can start building apps, master data analysis, and potentially land a job where you can write Python code.
Python resources
Python (wikipedia.org)
Python 3 Readiness (py3readiness.org)
You might be wondering: How and why should I start learning Python? To help you answer that, we’ll look at various programming languages and compare a few popular ones with Python. You'll find out why Python is a useful tool to have under your belt whether you are learning your first language or looking to learn an additional one. You’ll find out why Python is especially a good language to learn for first-time developers.
Before you learn Python learn web development basics
Before we install Python, let's think about where we need to start with it, and what we want to build.
Web Applications are tools you access over the internet. You open up a browser, and go to a website, and load an application - which lives on someone else's computer, but is being shown to you through your browser.
Front-end vs. back-end
Every application has both a front-end and a back-end.
The front-end is what you see on the browser, and the back-end is what handles the work behind the scenes: a database that stores everything you need, and rules, which connect the information in your database to the way you want it seen on someone's browser.
Front-end languages:
HTML
CSS
Javascript
Back-end languages:
Python
Ruby
PHP
Databases:
SQL
MySQL
Postgres
SQLite
We look at the history of Python and explore the differences between Python 2 and Python 3. For the course, we use (and recommend) Python 3. Python 2 is legacy, Python 3 is the future and so we recommend learning the latter. The two versions share similarities, so if you learn Python 3, you will still be able to read and understand any legacy Python 2 code you might come upon.
Python 2 vs. Python 3
In this class, we're going to use Python 3. In short, Python 2 is a legacy language (meaning its old!), and Python 3 is the future.
1. Install Sublime Text
Before we write our first line of Python code, you'll need to install a text editor (sometimes called an IDE). In this course, we'll be using Sublime Text.
Go to SublimeText.com and download the installer for Sublime Text (Mac or PC, Free software)
Install Sublime Text (the latest version) and make sure it's easily accessible on your computer.
If a window pops up saying something like "unregistered evaluation version," then click "cancel" and you can remain using the free trial mode indefinitely.
2. Install Python
There are several ways to install Python on your computer. We'll be using a simple installer called Anaconda.
Download the Python 3.6+ version Anaconda installer for Windows, OSX, or Linux.
Accept all the defaults during installation (just click "Continue" or "Next" the whole way).
If you run into the following error (see below) click "Install for me only" again and you should be able to continue. *Windows Users should check the "install to PATH" option even though it tells you NOT to do this and turns red.*
Once the installation has finished, restart your computer.
3. Set Up Your Command Line
The command line is where you run your code once you've written it, and its already installed by default on most computers.
Follow these instructions to get Terminal (the OSX version) or PowerShell (the Windows version) set up.
Get your Terminal, shell, or PowerShell working so you can access it quickly and know that it works.
Mac OSX
For Mac OSX you'll need to do this:
Hold down the command key and hit the spacebar.
In the top right the blue "search bar" will pop up.
Type: terminal
Click on the Terminal application that looks kind of like a black box.
This will open Terminal.
You can now go to your dock and CTRL-click to pull up the menu, then select Options->Keep In dock.
Now you have your Terminal open and it's in your dock so you can get to it.
Linux
I'm assuming that if you have Linux then you already know how to get at your Terminal. Look through the menu for your window manager for anything named "Shell" or "Terminal."
Windows
On Windows we're going to use PowerShell. People used to work with a program called cmd.exe, but it's not nearly as usable as PowerShell. If you have Windows 7 or later, do this:
Click Start.
In "Search programs and files" type: powershell
Hit Enter.
If you don't have Windows 7, you should seriously consider upgrading. If you still insist on not upgrading then you can try installing it from Microsoft's download center. Search online to find "powershell downloads" for your version of Windows. You are on your own, though, since I don't have Windows XP, but hopefully the PowerShell experience is the same.
The "Do More" section is optional. We'll be going over that in class.
Complete exercises 2, 3, 4, 5, and 6 to get familiar with the command line. We'll be using it throughout the course. (This step is also optional but HIGHLY recommended.)
Common Issues Installing Python
Make sure you restart your computer after running the Python installer.
Make sure you only type python in the prompt (no quotes, no spaces, no punctuation, nothing).
You may have to disable antivirus temporarily.
If you're on a work computer and it doesn't let you install Python or Sublime Text then you may need to contact your IT team and request permission.
"How do I know which version of Python I have?" is one of the most common questions I hear from students. In this lecture, I'll show you how to verify that you set up your development environment right. You'll test your Python installation and ensure that you have the right version of Python installed—version 3.0 or later.
Verify that you have Python installed
Open a new command line window (Terminal or PowerShell, depending on which your using).
Type python and hit enter.
If you see the words Python 3.6.X and Anaconda like above, your all set!
Type exit() or press Crtl-D to leave this prompt.
Common Issues Installing Python
Restart your computer after running the Python installer.
Type python in the prompt (no quotes, no spaces, no punctuation).
Disable antivirus temporarily (if this applies to you).
If you're using a work computer and it won't allow you to install Python or Sublime Text — you may need to contact someone on your IT team to grant you special permissions.
Troubleshooting: Want to remove (base)?
Some Apple computers may begin to show the prefix (base) on the command line. It's completely harmless if you just want to leave it alone. Although, if you'd like to remove (base) the following command should do the trick.
conda config --set changeps1 False
Just open a new command line window, paste in the code, and hit enter. Then restart the command line and it should be removed.
Troubleshooting for Windows?
When you’re installing Python, please make sure that you check "install to PATH". For windows, this is what allows you to call the "python" function from anywhere in your computer. You can also add manually to PATH, it’s just a little more advanced.
In this lesson, you'll be introduced to the Command Line, aka the Terminal. We'll show you how to customize your Terminal and then we'll take you through some example Bash commands that you can execute on the Command Line. The Command Line will be used to manage your Python projects and run your Python Code. The commands you learn here will be used throughout the course.
What is the command line?
Command line
Last login: Thu Apr 13 13:10:07 on ttys000
One-Month-Mac-mini-mattangriffel$ pwd
/Users/mattangriffel
One-Months-Mac-mini-mattangriffel$
The command line (aka. terminal on the Mac) is where we're going to run our Python code. This second line is the prompt - where you can type your code or anything at all. When you are reading Python code the $ symbol means that those commands should be run in the command line (as opposed to the text editor).
Learn command line basic
$ pwd # print working directory, ie. the folder that you are currently in.
$ open . # Use "start ." on Windows instead of open
$ ls # Use "dir" on Windows — This command will show you what's in you're current folder.
$ cd Desktop # change you're location to 'Desktop.'
$ cd .. # Go back to the folder behind the current folder.
$ cd ~ # Go back to main directory.
$ clear # clears everything above.
$ mkdir python #Windows: use "echo.> python.py" — Creates a folder called Python.
Customize your command line (Mac Only)
Terminal -> Preferences -> Settings
Select the "Homebrew" theme on the left side
Change the font to Menlo and font size to 18px
Choose "Default"
"Permission denied" error? (Mac only)
If you get a permissions error somewhere along the line, you might be able to use "sudo", which is your superuser account (aka. it's like the admin of your computer that has all the privileges.) For example:
$ sudo pwd
Let's run our first Python script! In this lesson, you'll learn how to navigate the file system with the command line as well as how to run Python scripts. If you browse Github for "Python scripts" you'd see that there are so many useful Python scripts (available for free!), but before you dive in too deep we need to start with the basics: your first Python script!
Download the file
Download happy_hour.py and move it into a new folder on you're Desktop
Download the ZIP
$ ls
happy_hour.py
Run the file
Remember you may have to use the python3 command instead of python depending on how your system is set up.
To run the file, type:
$ python happy_hour.py
The results should be interesting!
$ python happy_hour.py
How about you go to The Dead Poet with tha tperson you forgot to text back?
$ python happy_hour.py
How about you go to The Hamilton with Samule L. Jackson?
$ python happy_hour.py
How about you go to Lion's Head Tavern with Samule L. Jackson?
NOTE: Do not type the word 'Python' because that will lead the command line to a different place. If you find that $ python happy_hour.py or $ ls return error messages, type (exit) or hit control+D, which will take you back to where you need to be.
Open the file
When you open the file in Sublime it should look like this:
# What Should I Do Tonight?
import random
# Our list of bars
bars = ["Lion's Head Tavern",
"The Hamilton",
"1020 Bar",
"Amsterdam Tavern",
"The Heights",
"The Dead Poet",
"Prohibition"]
# Our list of friends
people = ["Mattan",
"Chris",
"that person you forgot to text back",
"Alexander Hamilton",
"Samule L. Jackson"]
random_bar = random.choice(bars)
random_person = random.choice(people)
print(f"How about you go to {random_bar} with {random_person}?")
Now, go through happy_hour.py and read it out loud to yourself. See if you can get a sense of what's happening. Follow your gut instinct on what it says (don't overthink it). Then meet me in the next lesson.
In this lesson, we go through the Python code that you just ran in the last lesson line by line to understand what it does. You'll be introduced to Python syntax, how to store data in variables as well as how to print out information to the screen.
Step by Step Explanation
Here's a step-by-step breakdown of our Python code.
1. Top of the file
import random
This imports other code. A library called 'random' that later allows us to pick out a random bar or random person from our lists.
2. Lists of Bars & People
bars = ["Shoolbred's",
"The Wren",
"The Scratcher",
"ACME",
"Blind Barber"]
people = ["Mattan",
"Chris",
"that person you forgot to text back",
"Kanye West",
"Samuel L. Jackson"]
These are lists of bars and people. They are going to be pulled into...
3. Pick a random bar and a random person
random_bar = random.choice(bars)
random_person_one = random.choice(people)
This is where our script picks a random bar and a random person.
4. Print out the results
print(f"How about you go to {random_bar} with {random_person_one}
This line prints out the random bar and random person.
The best way to learn to code is by coding. In this lesson, you will dive into your first programming challenge. Don't be scared, let's dive in together! In the next lesson, we’ll review the solution (no peeking just yet).
Happy Hour Challenges
I misspelled Samuel L Jackson's name. Fix the typo.
Add another person to the list of people.
Change the script so it prints out two random people instead of one. (ex. How about you go to Lion's Head Tavern with Mattan and Chris?)
You just completed your first coding challenge! Cheers to you! In this lesson, I'll walk you through the solution to the challenge. I'll show you how to add data to a Python List, change the output of printed information and points out some syntax errors that you can run into—giving you a brief introduction to debugging, which will be covered in more depth in later lessons.
1. Change Samule L. Jackson's name
This one's pretty straightforward. All you have to do is go in and correct Colonel Nick Fury's name to Samuel L. Jackson, and remember to save the Sublime file before you try running the script in your terminal.
2. Add another person to the 'people' list
Simply type another name, and add a comma, so it would look like this:
people = ["Mattan",
"Chris",
"that person you forgot to text back",
"Kanye West",
"Samuel L. Jackson",
"Kosta"]
Again, remember to consistently save your work.
3. Add another person
This one is more involved. First, you have to create another category, like this:
random_bar = random.choice(bars)
random_person_one = random.choice(people)
random_person_two = random.choice(people)
And then you go to your function, and add it in.
print(f"How about you go to {random_bar} with {random_person_one} and {random_person_two}?")
Remember to save, and you're all set to run the script!
I want to introduce you to the concept of a randomizer script, and give you your next challenge!
Your Challenge
Write your own Python randomizer script.
Create your own version of the happy hour script. It can be ice cream or countries to visit or whatever.
There are two ways in which you can run Python code—by executing a script file with the python command, or by executing commands in the Interactive Shell. You have already done the former. In this lesson, you will be introduced to the Interactive Shell. You will learn how to launch it and use it to execute Python code.
There are two different ways to run Python code:
1. Run the .py file
There are two distinct ways you can run Python code. The first is to go directly into your Terminal app and move to the location with a Python script, as we did earlier. You can move to the Python folder, and then type $ python happy_hour.py
2. Use the interactive shell
You can also type "python" into the prompt, and it will take you to something called the interactive shell.
Type Python code here directly - basic math works, as does printing specific text strings. The interactive shell is a great place to test out specific bits of code before you add them to your script in sublime. And remember, when you want to get out of the interactive shell, you can use a function called exit(), or just hit control+D.
In this lesson, you will learn how to write code that prints data to the screen. Printing information shows us the output of our code, and it is also userful for debugging code. Watch and I'll share a few Python print examples, and then you can create print functions and arguments from scratch.
Sublime text tips for Python
Make sure you've saved your file in the right folder as .py, so its read correctly as a python file. You can also manually go to the bottom right corner and change the syntax of your sublime text file to highlight things for Python, right here:
Now, in happy_hour.py type:
print("Winter is coming.")
print("You know nothing", "Mattan Griffel")
And if you go back onto the command line and run the command python printing.py (or whatever you've saved your file as), you should be able to print:
One-Month-Mac-mini: python mattangriffel$ python printing.py
Winter is coming.
One-Month-Mac-mini: python mattangriffel$ python printing.py
Winter is coming.
One-Month-Mac-mini: python mattangriffel$
Now, it's your turn! Edit your script so that it prints out the lyrics of your favorite song or poem.
No developer writes perfect code all the time. One thing you should expect is that your code won't always work as expected. This lesson will show you how to read error messages that are output to the Terminal and how to identify the code that caused the error. Debugging is something we'll be using throughout the course, so by the time you complete it, you'll be quite adept at finding and fixing bugs in your code. In this lesson, I'll also show you how to get the most out of debugging with Google and StackOverflow.
How to read errors in Python
When I first copied over the poem into printing.py, I forgot to close out one of the lines with a parenthesis ). That led to the following error:
Command Line
SyntaxError: Missing parenthesus in call to 'print'
One-Months-Mac-mini-python mattangriffel$ python printing.py
File "printing.py", line 10
print ("then wisdom")
SyntaxError: invalid syntax
Sometimes error messages are clear, sometimes they are not. This error message is scary, but let’s check it out.
The first line tells you the file name and what line it thinks the error is on:
Command Line
One-Months-Mac-mini:python mattangriffel$ python printing.py
file "printing.py", line 10
The next line is the code in the file from this script and the ^ shows you where it thinks the error is. And the final line is the actual error message (you can use this to look up more information).
How to troubleshoot using StackOverflow
Whenever you get stuck, Google your error and see if you can find the solution on StackOverflow.
Here's how to get the most out of StackOverflow:
1. Search Google for the error message ("SyntaxError: invalid syntax").
2. Click on the link for Stack Overflow: The parentheses in the line before your error line is unmatched.
And indeed, if we look back into the code, we can see there's a missing parenthesis on line 9, which was carried forward onto the next line.
In the printing.py you will see:
print("my blood approves")
print("and kisses are a better fate"
print("then wisdom")
Remember, as you correct errors, always remember to save the Sublime file before you try running the code again.
To put it in perspective how much developers rely on StackOverflow, check out this joke from Reddit's /ProgrammingHumor.
You should strive to write code that is easily readable and understandable. Programming languages allow developers to add annotations (i.e. comments) along the way to help explain what the code is doing. Comments make life easier for you, and for anyone else who may read the code.
When you put a # symbol before any line of code in Python it means, "This is a comment" and that line will not run. You can use comments for troubleshooting, or for leaving notes describing what your code is supposed to do.
Edit printing.py:
# "since feeling is first" by e. e. cummings
print("since feeling is first")
print("who pays any attention")
print("to the syntax of things")
print("will never wholly kiss you;")
print("wholly to be a fool")
print("while Spring is in the world")
print()
print("my blood approves")
print("and kisses are a better fate"
print("then wisdom")
print("lady i swear by all flowers. Don't cry") # I love this line.
print("—the best gesture of my brain is less then")
print("you're eyelids' flutter which says")
print()
print("we are for each other: than")
print("laugh, leaning back in my arms")
print("for life's not a paragraph")
print()
print("and death i think is no parenthesis")
Variables are used to label and store data that can be referenced and manipulated by your code. You have already worked with variables in the code you've written so far. This lesson will dive deeper into variables. You'll learn the rules governing the naming of variables as well as some recommended industry conventions to follow.
What are variables in Python?
I bet you already understand variables. Take a look at this basic math:
a = 1
b = 2
c = a + b
c = ?
What is c? If you said c = 3 than your right.
a, b, and c are variables.
Variables are just nicknames for things in your code. They are like boxes you can put things in and take them out of.
Create a file called variables.py:
# Variables are just nicknames
# there plain, lowercase words
# examples: x, y, banana, phone_a_quail
name = "Mattan Griffel"
orphan_fee = 200
teddy_bear_fee = 121.80
total = orphan_fee + teddy_bear_fee
print(name, "the total will be", total)
Tip: Sublime will suggest variables for you to fill in, and if you hit Tab, it will auto-complete them.
When you run the file:
$ python variables.py
Mattan Griffel the total will be 321.08
Variables in Python
Must start with a lowercase letter.
Can have letters, numbers, and underscores (but no spaces).
Should use underscores (instead of spaces). E.g. your_name.
When you define a variable, the variable name has to go on the left. This won't work:
"Mattan Griffel" = name
One thing computers are great at is performing computations. In this lesson, we'll do some Math using Python. You'll learn how to use the common arithmetic operators (e.g. Addition, Subtraction, Multiplication, Division and Modulus) as well as the rules governing the order in which they are executed.
Python math functions
Python is famous for it's ability to do amazing things with numbers and math. Check out the operations that you can do in the comments:
# + plus
# - minus
# / divide
# * times
# ** exponentiation
# % modulo
# < less then
# > greater then
print("What is the answer to life, the universe, and everything?", int((40 + 30 - 7) * 2 / 3))
Remember that modulo basically divides one number by a number.
Let's practice some Python math
print("Is it true that 5 * 2 > 3 * 4?")
print(5 * 2 > 3 * 4)
print("What is 5 * 2?", 5 * 2)
print("What is 3 * 4?", 3 * 4)
Which gives this on the command line:
$ code python3 mymath.py
What is the answer to life, the universe, and everything? 42
Is it true that 5 * 2 > 3 * 4?
False
What is 5 * 2? 10
What is 3 * 4? 12
Remember that you can use parentheses in Python math the same way you would do in regular math.
In Python, whole numbers are called "integers" and numbers with decimals are called "floats." The good news is that once you learn how to use numbers in Python, the basic programming concepts are more or less the same in every other programming language including JavaScript, Java, PHP, and Ruby.
Integers vs. floats
In Python, whole numbers are called integers and numbers with decimals are called floats.
3 is an integer
3.0 is a float
You can convert between integers and floats in Python. You can also specify whether you want a float or an integer by wrapping it.
In programming, a string is a sequence of characters. They are usually used to store data in text form. Here, we explore the string format in Python. We see how to create them as well as how to deal with strings that contain special characters through what is referred to as Escaping. I'll also introduce you to Kanye West's "greatest pain."
Strings are text surrounded by quotes (single, double, or triple) quotes.
# Strings are text surrounded by quotes
# Both single (') or double (") or triple (""") quotes are used
# examples: "dinosaurs", '2112', "I'm lovin' it!"
Here's another example using a variable:
kanye_quote = "my greatest pain in live is that I will never be able to see myself perform live"
print("kanye_quote")
The command line will print out the string without the quotes. The Kanye quote is long, but if you want to break it up into multiple lines you can use triples-quotes """:
...
kanye_quote = """My greatest pain in life
is that I will never be able
to see myself perform live."""
...
But this will actually put newline breaks (\n) in between each line of the string. If you don't want those then you can avoid the newlines by putting a \ at the end of each line, or simply by printing it with print(kanye quote) in the interpretive shell.
Escaping quotes in strings
One problem is that if you want to put single or double-quotes inside your string, Python will think you're trying to end your string.
So if you want to use single or double-quotes in a string without closing it out, you have to "escape" it by putting a backslash (\) in front of it:
...
hamilton_quote = "Well, the word got around, they said, \"This kid's insane, man\""
print(hamilton_quote)
It never hurts to put a \ in front of a quotation mark. You can also add newlines or tabs to strings with \n and \t.
There are other characters you will need to escape. For example, in order to use a backslash in a string, you actually have to escape the backslash like this: \\.
Triple quotes are another way to use either single or double quotations within a string. Like so:
"""Well, the word got around, they said, "This kid's insane, man"""
Resources
Python Reference Manual: String Literals (docs.python.org)
Sometimes, you usually need to combine the values of two or more variables. How do you put a variable inside a string? Let me show you how!
Putting variables inside strings may seem complicated at first (it's just the syntax that's weird) but stick with it because it's pretty simple once you get it. Let's explore by adding the code from variables.py to the bottom of strings.py:
kanye_quote = """My greatest pain in life
is that I will never be able
to see myself perform live."""
print(kanye_quote)
hamilton_quote = 'Well, the word got around, they said, "This kid\'s insane, man"'
print(hamilton_quote)
name = "Mattan Griffel"
orphan_fee = 200
teddy_bear_fee = 121.8
total = orphan_fee + teddy_bear_fee
If you wanted to combine the variables and the string, you can use the syntax below. Compare it to the original way we printed the string:
# print(name, "the total will be", total)
print(f"{name} the total will be {total}")
This new method takes the variables and puts them directly into the string. This is called string interpolation.
You can also clean up the numbers in that result to make the total display a currency with two decimals like so:
# print(name, "the total will be", total)
print(f"{name} the total will be ${total:.2f}")
At some point in your programming career, you will write software that takes input from the user and processes it. This lesson covers how to do this. You will learn how to read and utilize user input. User input usually comes in the form of strings. Sometimes this isn't what your code needs and so we will show you how to cast this into an appropriate type.
The input function
We're going to practice collecting inputs from users. Create a file called input.py.
You can create variables which require the user to add information, the input, before printing the result. You can also create an interpolated string with the variables inside.
The thing about user input is that it always comes in the form of a string. So, if you wanted to calculate a user's age in dog years, you need to convert the user input into a number you can multiply by seven.
You could use the int() function to convert your string into an integer.
So one of the easiest ways to fix this inside your script is to wrap int() your age input variable, like so: int(input("How old are you?")). You could also theoretically do it for age_in_dog_years = as well.
As I mentioned, you will do a lot of debugging in this course. This is a crucial skill in every developer's toolset. By the time you are done with the course, you will have the skills to test and debug all sorts of code.
At the end of this week, when I went back to try to run happy_hour.py, I got the following error:
$ python happy_hour.py
Let's do some math!
('What is the answer to life, the universe, and everything?', 42)
Is it true that 5 * 2 > 3 * 4?
False
('What is 5 * 2?', 10)
('What is 3 * 4?', 12)
Traceback (most recent call last):
File "happy_hour.py", line 3, in <module>
import random
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 45, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ImportError: cannot import name log
...which is really weird. Its printing out part of the math.py file.
A quick Google search for the error message (ImportError: cannot import name log) put me on a Stack Overflow page.
Is it possible that you have a file named math.py in the same directory as the program you are running? If so python tries to import it before the math module.
Solution: Just rename it to something else.
Crazy! Just changing the name of math.py to something like numbers.py solved the problem.
We've looked at Python variables, strings, arithmetic operators, debugging, typecasting and more! Now, you will put this knowledge to use. It's assignment time!
Topics we've covered this week:
Command line basics (pwd, ls, cd, open / start, ., .., ~),
Two ways of running python code (python [filename], python)
Print: print()
Comments #
Variable assignment
Numbers (floats, integers) + math
Strings (", ', """)
Escaping stuff inside of strings
Variables inside strings
User input with input()
Now its time for you to put all of that knowledge to the test. Click the 'Submit Assignment' tab above and take the challenge!
Week 2 starts off with the solutions to last week’s assignment. In programming, there is usually more then one way of solving a problem, so if your solution looks a little different, don't worry about it being wrong. If you get the expected results than it is most likely a correct solution. Watch on to find out other ways you could have solved it!
Answers to the assignment
Here's how I would have made the tip calculator:
# Write a script that takes a dollar amount and recommennds a tip (15%, 18% and 20%)
# Get a name
name = input("What is you're name? ")
print(name)
total = int(float(input("What is you're bill sub-total? ").replace('$', '')))
print(total)
tip_15 = total * 0.15
tip_18 = total * 0.18
tip_20 = total * 0.20
print(f"15% is ${tip_15:.2f}")
print(f"18% is ${tip_18:.2f}")
print(f"20% is ${tip_20:.2f}")
And you can actually make it even shorter by doing the tip calculations inside the curly brackets:
# Write a script that takes a dollar amount and recommennds a tip (15%, 18% and 20%)
total = float(input("What is you're bill sub-total? ").strip('$'))
tip_15 = total * 0.15
tip_18 = total * 0.18
tip_20 = total * 0.20
print("Tip Suggestions:")
print("----------------")
print(f"15% is ${tip_15:.2f}")
print(f"18% is ${tip_18:.2f}")
print(f"20% is ${tip_20:.2f}")
Conditional statements (also known as if/than statements) let you define specific times when something should happen. For example,"if" you say yes "than" I'll tell you a joke. Or on a website, "if" you are logged into the site, "than" I will send you a special announcement. In this lesson, I'll show you how to write conditionals in Python.
Create a new file
Create a new file called if.py:
answer = input("Do you want to hear a joke? ")
if answer == "Yes":
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedberg (RIP)
Running the file, we see our joke, or we don't.
$ python if.py
Do you want to hear a joke? Yes
I'm against picketing, but I don't know how to show it.
$ python if.py
Do you want to hear a joke? No
$
How does == work in Python?
== checks to see whether two things are equal. It returns True if they are and False if they aren't.
$ python
>>> "Yes" == "Yes"
True
>>> "No" == "Yes"
False
Remember that even though they look similar, = and == are very different.
$ python
>>> answer = "Yes"
>>> answer == "Yes"
True
>>> answer = "No"
>>> answer == "Yes"
False
You can also use != to check if two things are different:
>>> answer != "Blue"
True
>>> answer != "No"
False
How does if work?
if will check to see if something is True and then run any indented code after (after the colon).
if True:
# Anything here will run
And accordingly:
if False:
# This will never run
One unique thing about Python is its use of whitespace as part of its syntax. Most programming languages use braces to denote blocks of code, but in Python you use whitespace. Watch this video and learn more!
Spaces vs. Tabs
Spaces and tabs are really important in Python.
To tab, you can either hit the tab key or hit the space bar four times. BUT, you'er only allowed to do them one way.
Use this Sublime Text customization and to make your life a lot easier.
Go to File > Preferences > Settings – User and make it look like this:
{
"translate_tabs_to_spaces": true
}
In this lesson, we expand our knowledge of Python conditional statements by looking at ways of checking for more than one condition by using the if...else, if...elif...else and nested if conditional statements.
if, elif, and else
In if.py:
answer = input("Do you want to hear a joke? ")
if answer == "Yes":
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedberg (RIP)
elif answer == "No":
print("Fine.")
else:
print("I don't understand.")
else lets you say what code you want to run if the if part doesn't turn out to be true.
You can also add another if condition below the if with elif (you can actually add as many elifs as you want).
In this lesson, we look at Python logical operators. The most popular ones you need to know are: and, or , not, ==, !=, >, and <. You'll also learn how to determine if a value is either True or False.
Logic Operators
The most popular truth terms in Python are: and, or , not, ==, !=, >, and <.
There's also in, which is a way of putting strings or variables together. As in:
$ python
>>> people = ["Mattan", "Chris", "Sarah"]
>>> "Mattan" in people
True
Time to put your newfound knowledge of Python logical operators to the test. In this lesson, you will download a .py (Python) file containing a list of conditional tests that evaluate to either True or False.
Time for some Boolean Practice!
True and True
False and True
1 == 1 and 2 == 1
"love" == "love"
1 == 1 or 2 != 1
True and 1 == 1
False and 0 != 0
True or 1 == 1
"time" == "money"
1 != 0 and 2 == 1
"I Can't Believe It's Not Butter!" != "butter"
"one" == 1
not (True and False)
not (1 == 1 and 0 != 1)
not (10 == 1 or 1000 == 1000)
not (1 != 10 or 3 == 4)
not ("love" == "love" and "time" == "money")
1 == 1 and (not ("one" == 1 or 1 == 0))
"chunky" == "bacon" and (not (3 == 4 or 3 == 3))
3 == 3 and (not ("love" == "love" or "Python" == "Fun"))
Did you work through the last challenge? If you didn't, we recommend you go back and work through it before proceeding. Practicing is the best way to learn coding (or anything else). If you worked through the challenge, watch this lesson for the solutions to each of the problems and see how you did!
Boolean Answers
Here's the full set of answers for our boolean logic problems.
True and True # True
False and True # False
1 == 1 and 2 == 1 # False
"love" == "love" # True
1 == 1 or 2 != 1 # True
True and 1 == 1 # True
False and 0 != 0 # False
True or 1 == 1 # True
"time" == "money" # False
1 != 0 and 2 == 1 # False
"I Can't Believe Its Not Butter!" != "butter" # True
"one" == 1 # False
not (True and False) # True
not (1 == 1 and 0 != 1) # False
not (10 == 1 or 1000 == 1000) # False
not (1 != 10 or 3 == 4) # False
not ("love" == "love" and "time" == "money") # True
1 == 1 and (not ("one" == 1 or 1 == 0)) # True
"chunky" == "bacon" and (not (3 == 4 or 3 == 3)) # False
3 == 3 and (not ("love" == "love" or "Python" == "Fun")) # False
In this lesson, we introduce the "or" logical operator. This operator returns True if at least one of the expressions it's evaluating return True, otherwise, it returns False. You will learn some rules regarding the order in which it evaluates expressions—knowing this could save you from some logical bugs in your code.
The "or" operator
In if.py:
answer = input("Do you want to hear a joke? ")
if answer == "Yes" or answer == "yes":
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedberg (RIP)
elif answer == "No" or answer == "no" :
print("Fine.")
else:
print("I don't understand.")
If you have several values and want to evaluate if a certain value is equal to any of the available values, you can either string together several comparison expressions with OR statements, or even better, you can place the values in a Python sequence—for instance, a list—and use the IN operator to check if your data is in the list. This makes the code succinct and more readable.
In
So how do you cover all the different ways that a user could respond to an input? Well, you can put together a list, and then use in to pull responses from that list:
In the if.py type:
answer = input("Do you want to hear a joke? ")
affirmative_responses = ["yes", "y"]
negative_responses = ["no", "n"]
if answer.lower() in affirmative_responses:
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedburg (RIP)
elif answer.lower() in negative_responses:
print("Fine.")
else:
print("I don't understand.")
In programming, there is always more than one way to solve a problem. However, you will find that some solutions are usually better than others. Whenever you write code, there is usually a way that code can be improved either for improved readability, better performance, or best practices. Two rules of thumb to remember when refactoring your code are: Keep it Simple and Don't Repeat Yourself.
Refactoring (aka. cleaning up) our code
Let's tidy up our code so that it is shorter and cleaner. We can take our original list and actually change the function to return a lower case version of a true input when it runs, which eliminates having to list out specific upper/lower cases. Like so:
answer = input("Do you want to hear a joke? ")
affirmative_responses = ["yes", "y"]
negative_responses = ["no", "n"]
if answer.lower() in affirmative_responses:
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedburg (RIP)
elif answer.lower() in negative_responses:
print("Fine.")
else:
print("I don't understand.")
And we can use .lower to eliminate the need for a list entirely:
answer = input("Do you want to hear a joke? ")
if answer.lower() in affirmative_responses:
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedburg (RIP)
elif answer.lower() in negative_responses:
print("Fine.")
else:
print("I don't understand.")
There are some hiccups that may result from refactoring (depending on what your input is) but in general, this is a great way to improve your code.
A list in Python is a collection of data. Lists can hold numbers, strings, boolean values (1 or 0), and other data structures (for instance, a list of lists!).
Python lists
Lists are basically that. Lists of things.
In lists.py:
the_count = [1, 2, 3, 4, 6]
stocks = ["AAPL", "GOOG", "TSLA"]
random_things = ["Puppies", 55, "Anthony Weiner", 1/2, ["Oh no", "A list inside a list"]]
A list can have anything you want inside it: numbers, strings, even lists inside of lists. That last one is an example of nesting structure. And if that makes your head hurt, break it down into smaller pieces.
In this lesson, I'll show you how to loop over the elements in a list. This might come in handy in situations where you need to perform certain operations on each item in a list.
For looping
You can use the for x in list syntax to loop over a list. The x is your variable name for the thing in the list. So this:
# this for-loop goes through a list
for number in the_count:
print("this is count", number)
Returns this:
One-Months-Mac-mini:python mattangriffel$ python lists.py
this is count 1
this is count 2
this is count 3
this is count 4
this is count 5
One-Months-Mac-mini:python mattangriffel$
You can also do this same thing with strings.
Note that in your for x in list statement, the list has to already exist, but the X is a new variable your creating. So, if we were to ask for i in random_list print ("Here's a random thing:", i) then it would return everything in random_list, including the list nested inside random_list!
Here's your next challenge: print out the squares of the numbers 1-10. If you need help, I'd suggest you learn how to use the following in Python: insert(), pop(), clear() and del.
Append and remove
You can add things to a list with the append() function, and remove things from a list with the remove() function.
# we can also build lists, first let's start with an empty one
people = []
people.append("Mattan")
people.append("Sarah")
people.append("Chris")
# now we can print them out too
print(people)
# and remove some
people.remove("Sarah")
print(people)
This means that now when we use a for x in list function, we can set up like this:
for person in people:
print("Person is:", person)
And it will display our two people remaining in the list.
Challenge
Here's a challenge: print out the squares of the numbers 1-10.
In this lesson, I'll show you how we can use a range function instead of a list. In Python, a range will give you a sequence of numbers that are between two provided values: a lower limit and an upper limit. The sequence starts at the lower limit and goes up to, but doesn't include the upper limit.
So now that you've had a chance to try it out yourself, let's look over how to print out a list of all the squares of each number from 1-10. You can do it by creating a list, like this:
# Challenge: Print out the square of the numbers 1 to 10
for number in range(1,2,3,4,5,6,7,8,9,10):
print(number, "squared is", number * number)
But in our quest to always keep our code as short and as clean as possible, let's look for another way to perform the same function. And in fact, there is: ranges.
Ranges
You can also use loops to do something a certain number of times with the range() function. It looks like this:
# Challenge: Print out the square of the numbers 1 to 10
for number in range(1,10):
print(number, "squared is", number * number)
And comes out on the terminal like so:
$ python loops.py
...
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100
Note: Ranges start at the first number and go up to (but don't include) the second number. So if you want to do something 10 times, you have to use range(1,11).
Here, we look at ways we can access list items as well as ways we can get other useful information about a list and its items. You will find out how to access individual items inside a list using an index (sequentially as well as in reverse order), and how to find the "length" of a list.
You can pull out parts of a list using [] after the name of the list, like this:
# here's how you access elements of a list
animals = ['bear', 'tiger', 'penguin', 'zebra']
first_animal = animals[0]
print(first_animal)
third_animal = animals[2]
print(third_animal)
You can also find the length of a list with len()
print("They're are this many things:", len(random_things))
Note two things:
The position of things in a list starts at 0, so to get the first thing you do [0].
You can go backwards through the list using negative numbers. The last thing in a list is always [-1].
There's also the function type() which will tell you what kind of thing anything is.
Now, when you're pulling things out of a list, you can also go backwards. So if you were to type another_list = random_things[-1], then you'd get the list at the very end of our list of random things.
Challenge time! You are going to use what you've learned so far to solve the famous FizzBuzz Coding Challenge. The challenge is one of the most common coding interview questions.
Here's the FizzBuzz challenge.
Create a new file called fizzbuzz.py:
# Write a program that prints the numbers from 1 to 100.
# But for multiples of three print "Fizz" instead of the number
# and for the multiples of five print "Buzz".
# For numbers that are multiples of both three and five print "FizzBuzz".
# Tip: % (modulo) tells you what's left over when you divide one number by another
# ex. number % 3 == 0
Good luck!
Here's the answer to FizzBuzz in Python. Hopefully, you gave the FizzBuzz challenge a try. Whether you got the solution or not, let's work through the logic together.
Step #1
First print out the numbers from 1 to 100:
for number in range(1,101):
print(number)
Step #2
Print "Fizz" if the number is divisible by 3:
for number in range(1,101):
if number % 3 == 0:
print("Fizz")
else:
print(number)
Step #3
Print "Buzz" if the number is divisible by 5:
for number in range(1,101):
if number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
Step #4
Print "FizzBuzz" if the number is divisible by 3 and 5:
for number in range(1,101):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
(Note that this new condition number % 3 == 0 and number % 5 == 0 has to go above the other two because otherwise the others run first.)
In this lesson, we look at Python dictionaries. A dictionary is an unordered, changeable and indexed collection that doesn't allow for duplicate members. It is similar to a list, in that it is a collection of objects, but the main difference between the two is that a list is ordered while a dictionary isn't.
We already have a lot of different data types, but dictionaries are super important in order to do a lot of really useful things in Python. Dictionaries are basically lists - but lists go in order. With dictionaries, we use can look up something using a special key (basically a string).
Create a file called dictionaries.py. Inside, follow this syntax:
# states = ['NY', 'PA', 'CA']
# states = ['New York', 'Pennsylvania', 'California']
# states = ['New York', 'NY', 'Pennsylvania', 'PA', 'California', 'CA']
states = {'NY': 'New York', 'PA': 'Pennsylvania', 'CA': 'California'}
Voila! You've just created a dictionary. The key value pair are the things on either side of the colon. Note that the key is the thing to the left of the colon, and it has to be a string. But the thing on the right is the value, and that can be any data type.
This is the main difference between dictionaries and lists. You can access anything inside of a dictionary using the key (a string). With lists, you have to access things by number. Lists also guarantee they'll return in a particular order, and dictionaries do not. This makes them fast.
Searching a dictionary
To pull out the value from a dictionary, we simply print the key.
If you try to access something that isn't in the dictionary, you'll get a key error. And if you ever get confused about what something is - a dictionary or a list - you can always use the type() function.
You can search for things in dictionaries using .get(). It lets you look something up without returning a key error.
You're also able to get all the keys in a given dictionary by printing .keys().
Adding things to a dictionary is actually pretty easy. And that will set the key, even if it doesn't already exist.
Dictionaries are super useful to specify the information. Compare the list, which is commented out, with the dictionary, which keeps track of Mattan's details in a much more robust way:
# user = ['Mattan', 70, 10.5, 'Brown', 'Brown']
user = {'name': 'Mattan', 'height': 70, 'shoe size': 10.5, 'hair': 'Brown', 'eyes': 'Brown'}
In this lesson, I'll show you how to iterate and access values in objects, as well as show you how to avoid errors.
Lists inside of dictionaries
Your gonna see lots of lists inside dictionaries and dictionaries inside lists. This can get kind of crazy but stick with me.
animal_sounds = {
"cat": ["meow", "purr"],
"dog": ["woof", "bark"],
"fox": []
}
We can do this for users as well.
mattan = {'name': 'Mattan', 'height': 70, 'shoe size': 10.5, 'hair': 'Brown', 'eyes': 'Brown'}
chris = {'name': 'Chris', 'height': 68, 'shoe size': 10, 'hair': 'Brown', 'eyes': 'Brown'}
sarah = {'name': 'Sarah', 'height': 72, 'shoe size': 8, 'hair': 'Brown', 'eyes': 'Brown'}
Create a list
But now let's create a list:
people = [mattan, chris, sarah]
print(people)
Remember that these variables inside our list are now all dictionaries. If you print the list, you'll get all the dictionaries.
If you wanted to just print out the height of each person, you can loop over the list people, and realize that they all have the same keys. So you could use person['height'] to get their height.
Loops
The loop looks like this:
for person in people:
print(person['height'])
Note this only works because I know all the dictionaries have the 'height' key. A safer option might be:
for person in people:
print(person.get('height'))
Functions are a core concept in just about any programming language. They are the most basic building blocks of programming and almost every task that a program runs happens inside a function. In this lesson, you'll learn everything you need to know about functions.
Functions are commands (or blocks of code) that can do magical things for us! Your probably already familiar with the concept of functions if you use Excel or Google Spreadsheets. So far, we've used a bunch of functions: print(), len(), lower(). But did you know you can write your own functions?
How to create a function in Python
Create a file called functions.py and type:
def greet(name):
The "def" defines the function that follows it. "Greet" is the name of the function. And then "name" is the argument or an input we place inside the function. Then we "return" a function that will print "Hey {name}!"
def greet(name):
return f"Hey {name}!"
Name isn't defined yet, but that's okay. We'll get to it when its called. And we can call it by typing print(greet('Mattan')). Or any other name you want. The whole thing looks like this:
def age_in_dog_years(age):
result = age * 7
print(age_in_dog_years(28))
Return is how you get back the result of whatever function your running. If you ever get a return of "None" back, it's probably because you forgot to return something.
It's also important to note that each function can only return one thing. If you want to return more than one thing, then you have to return a result as a list or a dictionary. You can also call functions inside of functions.
Remember: variables and functions look the same. You know something is a variable if it doesn't have (). All functions have ().
In this tutorial, you will learn how to write functions, arguments, and you'll learn about scope (no, not the mouthwash).
Function checklist
Function definitions begin with def
A function name can only contain characters or an _ (underscore)
Open parenthesis ( right after function name
Arguments are separated by commas
Each argument must be unique (no duplicate names)
Close parenthesis and use colon ):
Indent all lines of code in the function with a tab (required)
End function by de-indenting back to the same indent level as the def
Too many or too few function arguments
If you add too many or too few arguments into a function:
...
print_two(first_name, 28, "Oops")
...
And try to run the file, you'll get an error:
$ python functions.py
Traceback (most recent call last):
File "functions.py", line 16, in <module>
print_two(first_name, 28, "Oops")
TypeError: print_two() takes 2 positional arguments but 3 were given
Now, you can change the argument order in a function. It's pretty common and convenient.
print(concatenate(word_two='Mattan', word_one='Griffel'))
Everything that happens inside of a function is isolated from what happens outside a function. This is called scoping.
Time for another challenge! Good luck!
Your Challenge
Create a function called uppercase_and_reverse that takes a little bit of text, uppercases it all, and then reverses it (flips all the letters around) so that:
>>> uppercase_and_reverse("Do not go gentle into that good night.")
"THGIN DOOG TAHT OTNI ELTNEG OG TON OD"
Ready for the answers? Let's walk through the answers, step by step.
The first step is to define the function, using the syntax we covered in the last couple videos. It should look like this:
def uppercase_and_reverse(text):
Now, we need to actually build functionality (see what I did there?) inside of the function. Specifically we need to uppercase and reverse the text. The uppercasing is pretty straightforward:
def uppercase_and_reverse(text):
uppercase_text = text.upper()
.upper() takes care of that. But the reversing is a little trickier.
def uppercase_and_reverse(text):
uppercase_text = text.upper()
reverse_and_uppercase_text = uppercase_text[::-1]
return reverse_and_uppercase_text
This solution gets you there, but it's a little long. There's actually a simpler way to accomplish the same reversal. We can combine lines 33 and 34. Like so:
def uppercase_and_reverse(text):
uppercase_text = text.upper()
return uppercase_text[::-1]
We can also run both parts of this function on the same line. This is called chaining.
def uppercase_and_reverse(text):
return text.upper()[::-1]
This is a very simple, clean way of running the function. You can reverse the order, it's simply chained together.
And remember, if we were to define a function reverse(text) like this:
def uppercase_and_reverse(text):
return reverse(text.upper())
def reverse(text):
return text [::-1]
print(uppercase_and_reverse("banana")) # ANANAB
It doesn't matter that it comes after our function uppercase_and_reverse(text). The only thing that matters is that it exist before its called to do anything on line 37. But it's a good idea to keep things in order.
Your task is to do some debugging and fix my code. Give it a try, it's not too tough—everything you need to know to complete this project has been covered in the course so far. You may need to rewatch some videos. And finally, congrats! You've made it halfway through the course :)
Here is what the file your fixing should look like. Its up to you to get it there. Download errors.py to get started.
$ python errors.py
----------
I used to play sports.
Then I realized you can buy trophies. Now I am good at everything.
----------
This should be ninety-nine: 99
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.
96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.
95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.
94 bottles of beer on the wall, 94 bottles of beer.
Take one down and pass it around, 93 bottles of beer on the wall.
93 bottles of beer on the wall, 93 bottles of beer.
Take one down and pass it around, 92 bottles of beer on the wall.
92 bottles of beer on the wall, 92 bottles of beer.
Take one down and pass it around, 91 bottles of beer on the wall.
91 bottles of beer on the wall, 91 bottles of beer.
Take one down and pass it around, 90 bottles of beer on the wall.
90 bottles of beer on the wall, 90 bottles of beer.
Take one down and pass it around, 89 bottles of beer on the wall.
89 bottles of beer on the wall, 89 bottles of beer.
Take one down and pass it around, 88 bottles of beer on the wall.
88 bottles of beer on the wall, 88 bottles of beer.
Take one down and pass it around, 87 bottles of beer on the wall.
87 bottles of beer on the wall, 87 bottles of beer.
Take one down and pass it around, 86 bottles of beer on the wall.
86 bottles of beer on the wall, 86 bottles of beer.
Take one down and pass it around, 85 bottles of beer on the wall.
85 bottles of beer on the wall, 85 bottles of beer.
Take one down and pass it around, 84 bottles of beer on the wall.
84 bottles of beer on the wall, 84 bottles of beer.
Take one down and pass it around, 83 bottles of beer on the wall.
83 bottles of beer on the wall, 83 bottles of beer.
Take one down and pass it around, 82 bottles of beer on the wall.
82 bottles of beer on the wall, 82 bottles of beer.
Take one down and pass it around, 81 bottles of beer on the wall.
81 bottles of beer on the wall, 81 bottles of beer.
Take one down and pass it around, 80 bottles of beer on the wall.
80 bottles of beer on the wall, 80 bottles of beer.
Take one down and pass it around, 79 bottles of beer on the wall.
79 bottles of beer on the wall, 79 bottles of beer.
Take one down and pass it around, 78 bottles of beer on the wall.
78 bottles of beer on the wall, 78 bottles of beer.
Take one down and pass it around, 77 bottles of beer on the wall.
77 bottles of beer on the wall, 77 bottles of beer.
Take one down and pass it around, 76 bottles of beer on the wall.
76 bottles of beer on the wall, 76 bottles of beer.
Take one down and pass it around, 75 bottles of beer on the wall.
75 bottles of beer on the wall, 75 bottles of beer.
Take one down and pass it around, 74 bottles of beer on the wall.
74 bottles of beer on the wall, 74 bottles of beer.
Take one down and pass it around, 73 bottles of beer on the wall.
73 bottles of beer on the wall, 73 bottles of beer.
Take one down and pass it around, 72 bottles of beer on the wall.
72 bottles of beer on the wall, 72 bottles of beer.
Take one down and pass it around, 71 bottles of beer on the wall.
71 bottles of beer on the wall, 71 bottles of beer.
Take one down and pass it around, 70 bottles of beer on the wall.
70 bottles of beer on the wall, 70 bottles of beer.
Take one down and pass it around, 69 bottles of beer on the wall.
69 bottles of beer on the wall, 69 bottles of beer.
Take one down and pass it around, 68 bottles of beer on the wall.
68 bottles of beer on the wall, 68 bottles of beer.
Take one down and pass it around, 67 bottles of beer on the wall.
67 bottles of beer on the wall, 67 bottles of beer.
Take one down and pass it around, 66 bottles of beer on the wall.
66 bottles of beer on the wall, 66 bottles of beer.
Take one down and pass it around, 65 bottles of beer on the wall.
65 bottles of beer on the wall, 65 bottles of beer.
Take one down and pass it around, 64 bottles of beer on the wall.
64 bottles of beer on the wall, 64 bottles of beer.
Take one down and pass it around, 63 bottles of beer on the wall.
63 bottles of beer on the wall, 63 bottles of beer.
Take one down and pass it around, 62 bottles of beer on the wall.
62 bottles of beer on the wall, 62 bottles of beer.
Take one down and pass it around, 61 bottles of beer on the wall.
61 bottles of beer on the wall, 61 bottles of beer.
Take one down and pass it around, 60 bottles of beer on the wall.
60 bottles of beer on the wall, 60 bottles of beer.
Take one down and pass it around, 59 bottles of beer on the wall.
59 bottles of beer on the wall, 59 bottles of beer.
Take one down and pass it around, 58 bottles of beer on the wall.
58 bottles of beer on the wall, 58 bottles of beer.
Take one down and pass it around, 57 bottles of beer on the wall.
57 bottles of beer on the wall, 57 bottles of beer.
Take one down and pass it around, 56 bottles of beer on the wall.
56 bottles of beer on the wall, 56 bottles of beer.
Take one down and pass it around, 55 bottles of beer on the wall.
55 bottles of beer on the wall, 55 bottles of beer.
Take one down and pass it around, 54 bottles of beer on the wall.
54 bottles of beer on the wall, 54 bottles of beer.
Take one down and pass it around, 53 bottles of beer on the wall.
53 bottles of beer on the wall, 53 bottles of beer.
Take one down and pass it around, 52 bottles of beer on the wall.
52 bottles of beer on the wall, 52 bottles of beer.
Take one down and pass it around, 51 bottles of beer on the wall.
51 bottles of beer on the wall, 51 bottles of beer.
Take one down and pass it around, 50 bottles of beer on the wall.
50 bottles of beer on the wall, 50 bottles of beer.
Take one down and pass it around, 49 bottles of beer on the wall.
49 bottles of beer on the wall, 49 bottles of beer.
Take one down and pass it around, 48 bottles of beer on the wall.
48 bottles of beer on the wall, 48 bottles of beer.
Take one down and pass it around, 47 bottles of beer on the wall.
47 bottles of beer on the wall, 47 bottles of beer.
Take one down and pass it around, 46 bottles of beer on the wall.
46 bottles of beer on the wall, 46 bottles of beer.
Take one down and pass it around, 45 bottles of beer on the wall.
45 bottles of beer on the wall, 45 bottles of beer.
Take one down and pass it around, 44 bottles of beer on the wall.
44 bottles of beer on the wall, 44 bottles of beer.
Take one down and pass it around, 43 bottles of beer on the wall.
43 bottles of beer on the wall, 43 bottles of beer.
Take one down and pass it around, 42 bottles of beer on the wall.
42 bottles of beer on the wall, 42 bottles of beer.
Take one down and pass it around, 41 bottles of beer on the wall.
41 bottles of beer on the wall, 41 bottles of beer.
Take one down and pass it around, 40 bottles of beer on the wall.
40 bottles of beer on the wall, 40 bottles of beer.
Take one down and pass it around, 39 bottles of beer on the wall.
39 bottles of beer on the wall, 39 bottles of beer.
Take one down and pass it around, 38 bottles of beer on the wall.
38 bottles of beer on the wall, 38 bottles of beer.
Take one down and pass it around, 37 bottles of beer on the wall.
37 bottles of beer on the wall, 37 bottles of beer.
Take one down and pass it around, 36 bottles of beer on the wall.
36 bottles of beer on the wall, 36 bottles of beer.
Take one down and pass it around, 35 bottles of beer on the wall.
35 bottles of beer on the wall, 35 bottles of beer.
Take one down and pass it around, 34 bottles of beer on the wall.
34 bottles of beer on the wall, 34 bottles of beer.
Take one down and pass it around, 33 bottles of beer on the wall.
33 bottles of beer on the wall, 33 bottles of beer.
Take one down and pass it around, 32 bottles of beer on the wall.
32 bottles of beer on the wall, 32 bottles of beer.
Take one down and pass it around, 31 bottles of beer on the wall.
31 bottles of beer on the wall, 31 bottles of beer.
Take one down and pass it around, 30 bottles of beer on the wall.
30 bottles of beer on the wall, 30 bottles of beer.
Take one down and pass it around, 29 bottles of beer on the wall.
29 bottles of beer on the wall, 29 bottles of beer.
Take one down and pass it around, 28 bottles of beer on the wall.
28 bottles of beer on the wall, 28 bottles of beer.
Take one down and pass it around, 27 bottles of beer on the wall.
27 bottles of beer on the wall, 27 bottles of beer.
Take one down and pass it around, 26 bottles of beer on the wall.
26 bottles of beer on the wall, 26 bottles of beer.
Take one down and pass it around, 25 bottles of beer on the wall.
25 bottles of beer on the wall, 25 bottles of beer.
Take one down and pass it around, 24 bottles of beer on the wall.
24 bottles of beer on the wall, 24 bottles of beer.
Take one down and pass it around, 23 bottles of beer on the wall.
23 bottles of beer on the wall, 23 bottles of beer.
Take one down and pass it around, 22 bottles of beer on the wall.
22 bottles of beer on the wall, 22 bottles of beer.
Take one down and pass it around, 21 bottles of beer on the wall.
21 bottles of beer on the wall, 21 bottles of beer.
Take one down and pass it around, 20 bottles of beer on the wall.
20 bottles of beer on the wall, 20 bottles of beer.
Take one down and pass it around, 19 bottles of beer on the wall.
19 bottles of beer on the wall, 19 bottles of beer.
Take one down and pass it around, 18 bottles of beer on the wall.
18 bottles of beer on the wall, 18 bottles of beer.
Take one down and pass it around, 17 bottles of beer on the wall.
17 bottles of beer on the wall, 17 bottles of beer.
Take one down and pass it around, 16 bottles of beer on the wall.
16 bottles of beer on the wall, 16 bottles of beer.
Take one down and pass it around, 15 bottles of beer on the wall.
15 bottles of beer on the wall, 15 bottles of beer.
Take one down and pass it around, 14 bottles of beer on the wall.
14 bottles of beer on the wall, 14 bottles of beer.
Take one down and pass it around, 13 bottles of beer on the wall.
13 bottles of beer on the wall, 13 bottles of beer.
Take one down and pass it around, 12 bottles of beer on the wall.
12 bottles of beer on the wall, 12 bottles of beer.
Take one down and pass it around, 11 bottles of beer on the wall.
11 bottles of beer on the wall, 11 bottles of beer.
Take one down and pass it around, 10 bottles of beer on the wall.
10 bottles of beer on the wall, 10 bottles of beer.
Take one down and pass it around, 9 bottles of beer on the wall.
9 bottles of beer on the wall, 9 bottles of beer.
Take one down and pass it around, 8 bottles of beer on the wall.
8 bottles of beer on the wall, 8 bottles of beer.
Take one down and pass it around, 7 bottles of beer on the wall.
7 bottles of beer on the wall, 7 bottles of beer.
Take one down and pass it around, 6 bottles of beer on the wall.
6 bottles of beer on the wall, 6 bottles of beer.
Take one down and pass it around, 5 bottles of beer on the wall.
5 bottles of beer on the wall, 5 bottles of beer.
Take one down and pass it around, 4 bottles of beer on the wall.
4 bottles of beer on the wall, 4 bottles of beer.
Take one down and pass it around, 3 bottles of beer on the wall.
3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottles of beer on the wall.
1 bottles of beer on the wall, 1 bottles of beer.
Take one down and pass it around, 0 bottles of beer on the wall.
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
"I think its interesting that 'cologne' rhymes with 'alone'" has 9 words
The words are: ['I', 'think', "its", 'interesting', 'that', "'cologne'", 'rhymes', 'with', "'alone'"]
The sorted words are: ["'alone'", "'cologne'", 'I', 'interesting', "its", 'rhymes', 'that', 'think', 'with']
I
'alone'
I
'alone'
This lesson kicks off the Data Analysis section of the course. Python is widely used in such fields as Data Science and Machine Learning. This is one of the reasons it is so popular. We're going to be doing our data analysis work with a program called Jupyter Notebook. It comes with the Python installer, so you should already have it installed.
We're going to be doing our data analysis work through a program called Jupyter Notebook. Good news, you already have Jupyter Notebook on your computer because it came with our Python installer! So we're all ready to go.
Let's start by downloading two files:
Download Files
notebook_intro.ipynb
imdb_top_10000.txt
Download the following two files and place them with your other Python files. The extension .ipynb is short for iPython Notebook, the original name before it changed to Jupyter Notebook.
We do a little bit more exploring with Jupyter Notebook. Jupyter Notebook enables you to run Python code inside of a notebook. You can also visually represent what your doing and share it with others.
One of the great things about Jupyter Notebook is that you can run Python code inside of a notebook. And, it allows you to visually represent what you're doing and show people how you're running your Python code.
To analyze data, we are going to need to learn pandas —an open source Python Data Analysis Library. In this pandas tutorial, we'll import data, and then you'll learn Python best-practices for parsing and structuring data.
So now, let's explore some of what Jupyter Notebook can do. Open Jupyter Notebook with the command:
$ jupyter notebook
Once you've got it open:
Click "New" and create a new file named data_analysis_intro
We'll start by adding some text in markdown (if you want to learn more about markdown, here's a handy-dandy markdown cheat sheet). Once we've typed our header: #Import Pandas, we can go out and get pandas.... the Python data analysis library, not the endangered animal.
Shift+Enter will run the file.
import pandas as pd
Now that we have pandas, we'll create another section called # Importing Data. From there, you can take the data file of imdb top films and pass it through Pandas.
pd.read_csv('imdb_top_10000.txt')
Now, you'll note that pandas has specified a csv (comma separated value) file, which is basically like an excel sheet. Our imdb file is a .txt file separated by tabs, so you'll have to specify the separator. To do this, you can simply add sep="\t"
pd.read_csv('imdb_top_10000.txt', sep="\t")
Now, =when you run it, you should see a table of films.
Next step for this particular file is to add headers for our table:
We can also tailor our columns so that the first one we see is our id column, like so:
Now that we have a table just the way we like it, we can call it data = and keep going!
names = ['id','title','year','rating','votes','length','genres']
data = pd.read_csv('imdb_top_10000.txt', sep="\t", names=names, index_col=0)
Now that we have some data loaded up, let's explore it with the pandas library. pandas provides some useful functions that you can use to get some information about your dataset or that you can use to filter the data. In this lesson let's look at the pandas functions data.head(), data.tail(), data.info(), and data.describe().
If we just run data, it'll be the entire table, and it's way too long to actually read all Top 10,000 films on IMDB. But, we can manipulate our data and explore patterns in Jupyter Notebook.
data.head() will us the first five results out of the entire set. You can also specify a number to only get back that particular number.
data.tail() will, naturally enough, give you the last five results in the set.
data.info() will tell you how many values you have in each other, and give you information about each column, and the types of each column - string, integer, float, object, etc.
data.describe() will give you information on all of the number columns - the mean, the standard deviation, etc.
Pandas enables you to export data to a file. You can configure how you want the data saved by specifying such settings as the file name, file type (e.g. .csv or .txt), separators (CSV files use commas), etc.
Let's create another markdown column # Exporting Data, and explore how exporting works.
The function we run to export data is data.to_csv('filename'), where 'filename' is the name of the file you want to save your data as.
You can specify farther for your header, index, and separators (remember csv files are separated by commas).
data.to_csv('test.csv', header=True, index=True, sep=',')
You now have a file you've converted a .txt file to a .csv file. Which is pretty cool. But with Python, we can do all sorts of other things to our data as well.
Let's learn how to sort our data. For this, you use the data.sort_values(by='') function. Whatever is between the quotes represents the column you want to sort by. You can also specify the order you want the sorted data in by passing in an argument: ascending=False or ascending=True.
There's an easy function that will help us sort our data: data.sort_values(by='')- with whatever is in between quotes representing a column we want to work with. If we were to run sort by rating, our table would display starting with the lowest ratings.
If we wanted to look at the highest rating first, we would have to add the argument:
data.sort_values(by='rating', ascending=False)
So far, we've been using a data structure from the Pandas library called a DataFrame. According to the documentation, a DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). In simpler words, DataFrames are the tables we see when pandas runs our data. Underneath, a DataFrame is just a Python dictionary with lists inside of it. We look at how to create a DataFrame from scratch.
The tables that we see when pandas runs our data are called data frames. But all data frames really are, is a Python dictionary with lists inside of it. You can create data frames from scratch if you want. Like, say, this one:
Create a dictionary
sample_data = {
'tv': [230.1, 44.5, 17.2],
'radio': [37.8, 39.3, 45.9],
'news': [69.2, 45.1, 69.3],
'sales': [22.1, 10.4, 9.3]
}
Pass in sample_data
data2 = pd.DataFrame(sample_data)
Display the new data
data2
Remember, its not in order because dictionaries do not guarantee an order
If you want to delete the data2 frame?
del data2
When analyzing a data set, you might want to only deal with some portion of the data set. With Pandas, you can easily grab a subset of a set of data. You can, for instance, specify that you want a certain column (or a few columns) and you can even use some functions on the subset to get specific information about the subset, e.g. using max() to get the maximum value in a subset, or mean() to get the average of all values in a subset.
There are many different ways you can pull out specific columns of your data, depending on what you're looking for. But these are some good functions to have in your pocket as you sort through everything:
data['title']
data[['title', 'year']]
data['rating'].mean()
data['rating'].max()
data['rating'].min()
data['genres'].unique()
data['rating'].value_counts()
data['rating'].value_counts().sort_index()
Once we've evaluated our data, it can be useful to plot it and have it in a more visual form. In this lesson, we use the Matplotlib library to do this. Matplotlib is a Python 2D plotting library which produces figures in a variety of formats. With Matplotlib, you can easily generate plots, histograms, boxplots, power spectra, bar charts, pie charts, error charts, scatterplots, etc.
One of the more popular Python plotting libraries is Matplotlib. There are all sorts of formatting we could get into, but that would be a whole other class. For now, let's start by enabling Matplotlib in Jupyter Notebook by entering the command:
%matplotlib inline
Then, if we want to plot our data, it'll default to this:
That gives an image that we can save and send to someone, which is pretty cool. But, this graph doesn't tell us all that much, so we can do some other types of plotting. For instance, we can grab a scatter plot with:
data.plot(kind='scatter', x='rating', y='votes')
Let's look at another plotting library—Seaborn. Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
Import Seaborn
Another popular plotting library is Seaborn. In order to work with it, you'll need to import it:
import seaborn as sns
If it doesn't work right away, you can pip install it.
Seaborn pairplot
Note that you'll have to pass data into Seaborn a little differently, but you can still come up with a very cool graph:
sns.pairplot(data)
Note that it's a very similar plot as we got with Matplotlib, but there's an automatic linear regression that explains the data.
Another cool thing that Seaborn can do is a pair plot, which automatically plots all of the number columns against each other:
Now that we've visualized our data, we dig into an ordinary least squares (or OLS) regression. We use the StatsModels library to calculate this. StatsModels provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration.
If your interested in calculating stats, there's a library that can help you do that called StatsModels. In this lesson let's work on an ordinary least squares (or OLS) regression.
Import StatsModels (You can go to the Stats Models Org website for this)
import statsmodels.api as sm
Ordinary Least Square (OSL) Regression
From there, we can create sm.OLS() and pass in the data we want to check against each other. For instance:
results = sm.OLS(data["votes"], data["rating"]).fit()
And then to see the visual representation of those results use:
results.summary()
In this lesson, we go over even more data selection! We look at various ways to get more specific with the data we are working with.
You can get even more specific with the data your working with. For instance, if we wanted to look at all the data from after a particular year, we could specify
data[data['year'] > 1995]
How this works under the hood: if we were to only do the inside part, it would only return False/True, and basically just tell you if a film was made before or after 1995. But when you put that inside another data selection, it will only return the true values.
You can also find films from a particular year by using another one of our boolean friends:
data[data['year'] == 1966]
We can also grab a range with
data[(data['year'] > 1995) & (data['year'] < 2000)]
Note that the & works for and, and if you want to use an or, you have to use |. But that latter one is less useful because every movie was made either before or after a given year.
We can get super specific with this. For instance, if we want to know the top 10 rated movies in a given span of years, we can run:
data[(data['year'] > 1995) & (data['year'] < 2000)].sort_values(by='rating', ascending=False).head(10)
That will give us the top rated movies from 1996 through 1999.
Pandas can also be used to group things together in ways that make the data more understandable. After grouping the data according to some criteria, pandas makes available functions that you can use on the grouping to get specific information on it, e.g min() to get the minimum value in the group or mean() to get the group average.
We can also use pandas to group things together in ways that are useful to understand the data. So we can run the function:
data.groupby(data['year'])['rating'].mean()
This will give us the average rating for films in each year. You could also grab the maximum rating in each year with:
data.groupby(data['year'])['rating'].max()
And the minimum would be:
data.groupby(data['year'])['rating'].min()
Here are a few challenges that will test your data analysis skills.
Challenge Questions:
What was the highest scoring movie in 1996?
In what year was the highest rated movie of all time made?
What five movies have the most votes ever?
What year in the 1960s had the highest average movie rating?
Let's look at the answer to previous data analysis challenge.
The solutions
What was the highest scoring movie in 1996?
data[data['year'] == 1996].sort_values(by='rating', ascending=False).head()
In what year was the highest rated movie of all time made?
data[data['rating'] == data['rating'].max()]
What five movies have the most votes ever?
data.sort_values(by='votes', ascending=False).head()
What year in the 1960s had the highest average movie rating?
data[(data['year'] >= 1960) & (data['year'] <= 1970)].groupby(data['year'])['rating'].mean()
Data cleaning is a big part of data analysis. In order to run a proper analysis, you have to ensure that your data is clean and free of errors. In this lesson, we'll look at some tools in Python for cleaning up data.
Let's look at how to fix some of the problems with our data.
If we run:
data['title'].str[:-7],
This will cut off the last seven characters in the string, effectively deleting the years in the title.
You could also run:
data['formatted title'] = data['title'].str[:-7]
This will override in place of the column, but preserve the original data column, in case you've made any kind of mistake.
There's another way we could solve this problem, strategically looking for parentheses and splitting them (which splits something into a list):
data['title'].str.split('\(').str[0]
You could also do:
data['title'].str.split('\(').str.get(0)
Which way do you think is best?
Let's keep cleaning up our data set.
Let's work on cleaning up our length column, which requires a similar fix. We can run:
data['length'].str(-6)
which will get rid of the "min" after each number. We could also do the split method:
data['length'].str.split().str.get(0)
The only real problem here is that Jupyter still thinks this is a string, but we can quickly convert it into an integer with:
data['length'].str.split().str.get(0).astype('int')
We could also use:
data['length'].str.replace(' min ', ' ' ).astype('int)
When we turn this into a formatted length column the same way we created a formatted title column, and then we can see it properly in a pair plot with all the other number columns:
If you'd like to keep going as an exercise, you can use splitting to break up specific genres.
A quick shoutout to data.gov. If you are looking for data sets that you can use in your projects, then check them out. They have a wide variety of cool data sets that you can explore.
Check out data.gov for all kinds of cool data sets.
Flask is a Python framework that you can use to build full-stack web applications. In the next few lessons, I'll take you through the process of building out both the front-end and back-end with Python.
What is Flask?
Flask is a light-weight framework with a built-in server that will allow us to turn our Python scripts into webpages and web apps. To say that another way, Flask allows us to make websites with Python.
Let's see if Flask is installed
If you used Anaconda to install Python (as we did at the beginning of this course) then you should have Flask installed already.
To find out if you have flask type the following command on the command line:
$ Flask
If the text that appears says something like "A general utility script for Flask applications" and "Options" then you are good to go!
But if you see "command not found?" then you'll want to visit Flask and install Flask by running the command pip install flask.
Let's run our Flask server
Find the starter code on the Flask homepage. Paste that code into a new file called web.py.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
Run the server with the command
This command will run your Python script and more or less turn your command line application into a server.
$ FLASK_APP=hello.py flask run
To quit the server you'll need to press control-Z.
In this lesson, we turn debug mode on. Why? By default debug mode is off, meaning that we have to restart the server every time we make a change. Once we turn debug mode to on we can update our Python and HTML templates in real-time. Watch along, and let's see it in action!
Make life easier on yourself with debug mode
Every time you make a change in you're Python code, you'll have quit, and restart the server. Annoying right? Run this export FLASK_ENV command and your Python code will update in real-time, without having to restart:
$ export FLASK_ENV=development
If for some reason that didn't work, try adding these two lines to the bottom of your file:
if __name__=="_main_":
app.run(debug=True)
Note: The first time you add this code you'll need to shut down the Flask server and restart it.
In this lesson, we create our first webpage with Python using just the render_template method in Python and some HTML.
1. Python
Update your route file with the render_template method
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
2. Create
Create a new folder called "templates" and inside add index.html
3. Write some basic HTML inside index.html
<html>
<head>
<title>Flask App</title>
</head>
<body>
<h1>Hello I'm HTML</h1>
</body>
</html>
4. View the page in your browser
In the browser, you should now see your rendered HTML page. The URL will likely be 127.0.0.1:500
Now that we have our homepage up and running, it's time to add a second page. Let's call this one "About." In order to get a second-page working, we'll need to update the route, and create a new HTML file.
In this lesson, we set up a second route for our new page "about.html"
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/")
def about():
return render_template("about.html")
Includes allow us to create reusable snippets of code. In this lesson, we'll create a header and footer using includes.
1. Create header and footer includes
index.html
{% include 'header.html' %}
<h1>Homepage</h1>
{% include 'footer.html' %}
2. Move the head of your HTML into the header.html file
header.html
<html>
<head>
<title>
Homepage
</title>
</head>
<body>
<a href="/">Homepage</a>
<a href="/about">About Me</a>
<a href="/contact">Contact</a>
Now that we're using Flask, we can use conditional logic ("if else") in our HTML. This opens up a whole new world of possibilities!
1. Pass parameters to your template
hello.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
title = "Homepage"
return render_template("index.html", title=title)
@app.route("/about")
def about():
title = "About"
return render_template("about.html",title=title)
@app.route("/contact")
def contact():
title = "Contact"
return render_template("contact.html",title=title)
2. And use if, elif, else, and end as conditionals in your HTML
header.html
<html>
<head>
<title>
{% if title=="About" %}
About Page | OneMonth.com
{% elif title=="Contact" %}
Contact Page
{% else %}
OneMonth.com
{% endif %}
</title>
</head>
<body>
<a href="/">Homepage</a>
<a href="/about">About Me</a>
<a href="/contact">Contact</a>
Now that you know the basics of Flask you may want to consider learning the basics of Bootstrap to improve your layout, and Heroku in order to get your website live.
Download
All projects from this Python course are available to download.
“Forget Wall Street lingo. The language Citigroup Inc. wants its incoming investment bank analysts to know is Python” — Bloomberg
Learn Python is our introduction to Python programming course for total beginners. It is comprised of two crucial ingredients for learning how to code:
Project-based
Bite-sized content with weekly goals
What can you build with Python?
Python is one of the most popular coding languages of 2021. It is designed to be easy to read while still being very powerful, which makes it an ideal language for beginners. It’s not just for beginners, though. Python is used by thousands of world-famous companies including Google, Facebook, Dropbox, Instagram, and Reddit. It is most often used for building websites, data analysis, machine learning, and natural language processing.
Learning Python has even gone mainstream with dozens of jobs requiring Python skills such as financial advisors, data journalists, and digital marketers.
Is this Python course for beginners?
Yes! Our course assumes no previous knowledge of programming or code. We do, however, assume that you’re fairly comfortable using a computer (Mac or PC) and can navigate the internet using a web browser (we recommended Chrome!).
In just 30 days, Learn Python will take you from a beginner to an intermediate Python developer. Don't believe it? We guarantee it with our 100% Money-Back Guarantee* for anyone who completes the course.