- Go to colab.research.google.com
- If you already have a Google account, use that to sign in. If not, create an account.
- You’ll be shown a screen similar to the one below.

- Start a new notebook by click on the New notebook link in the bottom right corner of the popup window.
Jupyter Notebooks are comprise of cells – either for code or text. You can string these together to create an interactive page. Here are a few basic rules before we look at a few examples:
- Everything is a cell. You can click on a cell and run it.
- Code can be Python code or can be markdown
- All cells are given an execution number so you know what order they were run in.
- Keyboard shortcuts – but you have to be in command mode. To do that click outside of cell or the Esc key. To get back into edit mode click in a cell or the Return key. Some shortcuts:
- a adds a cell above,
- b adds one below
- dd deletes a cell
- arrow keys to move around
- switch type -m markdown; y – python
- Execute code – current selection – ctrl-return
- Execute code – current but moves to next – shift-return
Mount Your Drive
from google.colab import drive drive.mount(' /content/drive ')
Click the arrow key to run the code and allow it to access your Google Drive. Select the account you want to use. Click the Allow button and you should see this message.
Mounted at /content/drive
import pandas as pd from os import path DATA_DIR = '/content/drive/My Drive/data'
Here we are setting DATA_DIR to be a constant that is set to the path where the data is.
players=pd.read_csv(path.join(DATA_DIR, '2018-season','players.csv'))
| players.head() | shows the first 5 rows of the DataFrame |
| players.columns | an attribute which lists the columns found in a DataFrame |
| players.shape | an attribute which tells how many rows columns are in a DataFrame |
| String Method | Example |
|---|---|
| capitalize() Makes the first character upper case |
txt="hello world" txt.capitalize()="Hello world" |
| center(length, character) Centers the string in the amount of space specified by the length parameter. Optional Character specifies character to use. White space is the default. |
txt="hello world" txt.center(20,"!")= "!!!!hello world!!!!!" |
| count() Returns the number of times a string occurs in another string |
txt="Cats are smarter then dogs. Cats rule." txt.count("cats")= 2 |
| find(str_to_find, startpoint, endpoint) Finds a string in a string. Begins at starpoint which defaults to 0 and searches to endpoint which defaults to length of the string. |
txt="Cats are smarter then dogs. Cats rule." txt.find("Cat")= 0 txt.find("so")= 12 txt.find("Cat", 10)= 36 txt.find("fish")= -1 |
| format(parameter1, parameter2, ...) Allows you to put variables into your string. |
txt="Cats are {} then dogs. Cats {}." txt.format("smarter","rule")= Cats are smarter then dogs. Cats rule txt="Cats are {1} then dogs. Cats {0}." txt.format("rule","smarter")= Cats are smarter then dogs. Cats rule |
| lower() Makes every character lower case |
txt="HELLO World" txt.capitalize()"hello world" |
| replace(oldvalue, newvalue)replaces any occurrences of the old value with the new value in the string | txt="I think dogs are great. I love dogs."
txt.replace("dogs","cats") "I think cats are great. I love cats ." |
| strip() Removes any white space from the beginning or end of the string |
txt=" Hello world " txt.strip()="Hello world" |
| title() Makes the first character of every word upper case |
txt="hello world" txt.title()="Hello World" |
| upper() Makes everything upper case |
txt="hello world" txt.upper()="HELLO WORLD" |
Placeholders
Each character in a string can be accessed by the number of it's place in the string starting at 0. Huh? It works like this:
name= "Steve Jobs" name[0] => "S" name[4] => "e" name[5] => " " name[6] => "J"
Multiplying Strings
What? Multiplying? Is that even possible? Apparently so! Here's how it works:print (10 * 'a') Output is: aaaaaaaaaa
- Allows the user to enter data from the keyboard.
- It waits for the user to press the Enter key before taking the information.
- Returns a string.
The basic syntax is:
input("string that is displayed to the user")
Let's take a look at an example:
school = input('Enter the name of your school:') print("You go to", school)
The print() function displays information to the screen - it can display a combination of text and variables including adding separators.
Here's the basic syntax:
print(value1, value2, ...sep, end, file, flush)
A little more there then we initially learned. Here's what this all means:
| Parameter | What it does |
|---|---|
| value1, value2, ... | these are the values to print. Can just be one...can by many. Must be strings. |
| sep: | Optional: what character should be printed between the different values. The default is white space. What's nice about this is that we do not have to concatenate " " |
| end | Optional: what should be printed at the end - the default is '\n' which creates a new line. |
| file | Optional: what method to use to write - the default is sys.stdout. Don't worry about this one yet! |
| flush | Optional: same don't worry about this one yet but if you must know the default value is False which means the output should be buffered. |
Review of the Basics
print("Hello World!")
The print() function takes a string as its parameter. You can assign a value to variable and then print that variable. For example:
phrase = "Hello World" print(phrase)
Concatenating (or "adding" two strings )
Can concatenate strings by putting a plus sign (+) between them. Either like this:
print("Hello World! " + "It is a beautiful day.")
Using Commas to Concatenate
Can concatenate strings with commas when you are using a print() function - faster to type & run.
print("Hello World!", "It is a beautiful day.")
Or use a mix of variables and straight text.
print("Hello World!", phrase2)
Separating Output
You can separate things by a new line so every item is on a new line.
first= "chocolate" second = "gardening" third ="hot bath" print("Elizabeth\'s fav things are:", first, second, third, sep='\n')
This gives us this output:
Elizabeth's fav things are:
chocolate
gardening
hot bath
Ending Output
Similar to using separators between strings - this allows you to put something at the end of a string.
print("Today is a beautiful day", end='.') print("Today is a beautiful day", end='!')
This gives us this output:
Today is a beautiful day. Today is a beautiful day!
A condition is how we compare two things such as variables, numbers or strings. The comparison returns a value of True or False. In Python, the logical operators to compare two things are as follows:
Operator Description == Equal To != Not Equal To > Greater Than < Less Than >= Greater than or Equal to <= Less than or Equal to in Is a string contained within another string?
Now, we know how to check to see if a single condition is valid or not. But, often you are checking to see if multiple conditions are valid. For example, if it is Sunday and the weather is nice you can go swimming.
We use Boolean Operators to evaluate more than one condition.
| Operator | Description |
|---|---|
| and | If you want all of the conditions to be met or True |
| or | If you only care if 1 of the conditions is met or True |
| not | If you to not want the condition to be True. Or more basic - simply the opposite. |
Here are a few examples of comparing multiple conditions in Python code.
#Set a few variables inches_snow = 6 still_snowing = True temperature = 15 #Now compare the variables print(inches_snow > 5 and temperature < 32) => True print(inches_snow > 15 and temperature < 32) => False print(inches_snow > 15 or temperature < 32) => True print(inches_snow > 5 or (still_snowing and temperature < 32) => True print(inches_snow > 5 and (not still_snowing and temperature < 32) => False
Simple Examples
inches_snow = int(input("How much snow did you get?")) if inches_snow > 5: print('No School Today')
inches_snow = int(input("How much snow did you get?")) if inches_snow == 1: print('Go to school but wear boots')
#example of using 'in' favorite_animal = “bobcat” if ‘cat’ in favorite_animal: print(‘You like cats!')
Booleans & None
Now, let's look at a few examples using booleans and the None value.
#Using a boolean still_snowing=True if still_snowing: print ("Woot!!! Time to go sledding!! ) #Let's see an example using the not if not still_snowing: print ("Time to shovel... )
#Comment remember that 'None' is used when the variable is empty. age = None if age == None: print('You apparently have not been born yet!')
Full Example
inches_snow = int(input("How much snow did you get?")) if inches_snow> 5 and inches_snow < 12: print('No School Today') elif inches_snow >= 12 and inches_snow < 24: print('Obviously no school - go sledding!!!') elif inches_snow >= 24: print('Can you even open your front door?') else: print('Ha! Get up, eat breakfast and get to school') print('I hope you didn't forget to do your homework!')
