0% found this document useful (0 votes)
6 views12 pages

Class - 1 - Master - Jupyter Notebook

The document is a Jupyter Notebook that provides an overview of Python fundamentals, including data types, variables, math operators, control statements, data collections (lists and dictionaries), and functions. It also introduces object-oriented programming concepts and the use of Jupyter Notebook for coding in Python. The content is structured with code examples and explanations to help learners understand the basics of Python programming.

Uploaded by

rileyjones99999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views12 pages

Class - 1 - Master - Jupyter Notebook

The document is a Jupyter Notebook that provides an overview of Python fundamentals, including data types, variables, math operators, control statements, data collections (lists and dictionaries), and functions. It also introduces object-oriented programming concepts and the use of Jupyter Notebook for coding in Python. The content is structured with code examples and explanations to help learners understand the basics of Python programming.

Uploaded by

rileyjones99999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1/21/2021 Class_1_Master - Jupyter Notebook

Python 1 - Overview
Bootcamp will cover Python fundamentals while making a music playlist program

Evaluating primitive types in python: type()


Declaring variables and variable declaration conventions: =
Math Operators and string concatenation: (+ , - , * , /,%)
IF and WHILE statements with conditional operators: (==, >, >=, break)
User input: input()
Data collections - Lists: ([ ], append(), insert(), del, pop(), len(), sort())
Data collections - Dictionaries: ({ },[ ], insert(), del, clear(), keys(), values())
Declaring custom functions: def, return
Classes and object oriented programming: class(), __init__(), methods
Automating with FOR loops: for, in

Jupyter Notebook
This is a web-based application (runs in the browser) that is used to interpret Python code.

To add more code cells (or blocks) click on the '+' button in the top left corner
There are 3 cell types in Jupyter:
Code: Used to write Python code
Markdown: Used to write texts (can be used to write explanations and other key
information)
NBConvert: Used convert Jupyter (.ipynb) files to other formats (HTML, LaTex, etc.)

To run Python code in a specific cell, you can click on the 'Run' button at the top or press
Shift + Enter
The number sign (#) is used to insert comments when coding to leave messages for yourself
or others. These comments will not be interpreted as code and are overlooked by the program

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 1/12
1/21/2021 Class_1_Master - Jupyter Notebook

Data Types
Four primitive types in Python
1. Integers
2. Booleans
3. Floats
4. Strings
Types may be changed using int(), str(), float(), and bool() methods

In [1]: # The type() function will return the data type of the data passed to it

type("Hello!")

Out[1]: str

In [2]: type(True)

Out[2]: bool

In [3]: type(3.14)

Out[3]: float

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 2/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [4]: type(3)

Out[4]: int

In [5]: # Casting - converting from one data type to another


print(type(float(3)))
print(int(3.55))

<class 'float'>
3

In [6]: # Try to cast a string to a boolean so that it returns false


print(bool(''))

False

In [7]: # Try to cast an int to a boolean so that it returns false


print(bool(0))

False

Variables
May consist of letters, numbers, and underscores, but not spaces.
Cannot start with a number.
Avoid using Python keywords (for, if, and, or, etc.)
Be careful when using 1s and lower case ls, as well as 0s and Os.
Keep it short.
Example: phone_num = 647606
In Jupyter, we need to be very careful when running cells when we use variables!

In [8]: # In the code below, the variable `hours_worked` has been assigned
# an integer value of 10.
hours_worked = 10

In [9]: print(hours_worked)

10

Math Operators

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 3/12
1/21/2021 Class_1_Master - Jupyter Notebook

Addition, Subtration, Multiplication and Division may be done using basic math operators (+ , -
, * , /,%).
Python will also try to interpret your code with other data types
(+) may be used with strings!
However, the usability is limited, instead we will introduce functions

In [10]: # Create two variables, price1 and price2 that have float values representing the
price1 = 3.40
price2 = 2.51

# Create a new variable whose value is the sum of the prices


tot_price = price1 + price2
# Python can perform all the typical mathematical operations
diff_price = price1 - price2
mult_price = price1 * price2
div_price = price1 / price2
print(tot_price)

5.91

Functions
We cannot perform all math on strings, as it sometimes doesn't make sense
Instead we use functions, prewritten sets of instructions
To use a function on a string, we use the dot operator
The general form will be string_variable.function_name(function_arguments)
We'll talk more about functions later in the session

In [11]: #A few string functions


employment = "I work with python"
print(employment.title())
print(employment.lower())

print(employment.index("work"))
print(employment.split(" "))
print(employment.replace("python", "Finance"))

I Work With Python


i work with python
2
['I', 'work', 'with', 'python']
I work with Finance

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 4/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [12]: # With F strings, variables go directly into a string! Even methods!


name = "Seamus"
tool = "python"
print(f"{name} works with {tool.upper()}")

Seamus works with PYTHON

In [13]: # A boolean can only have one of two values. Either they are "True" or "False".
# Variables "yes" and "no" have been assigned boolean variables of "True" and "Fa

yes = True
no = False

IF and WHILE Statements


Will only run indented code if condition is true
Make use of conditional operators to create tests
(==) will return true if both variables are equal
(>) will return true if left variable is larger
(>=) will return if left variable is larger or equal to right variable
IF will only run indented code once, WHILE will run indented code until condition is no longer
true

In [14]: # Boolean variables are generally used for conditional statements such as an if s
# The below lines of code uses boolean variables to determine whether or not the
if yes:
print("True Statement!")

if no:
print("Will not print")

True Statement!

In [15]: #New variable to keep track of total number of employees


dept_size = 10

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 5/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [16]: # if else statments can also be used with math or anything really (like strings)!

if dept_size >=0 and dept_size < 20:


print(f"Small Department: {dept_size}")
elif dept_size < 50:
print(f"Medium Department: {dept_size}")
else:
print(f"Large Department: {dept_size}")

Small Department: 10

In [17]: # While loops will keep running a loop of code until the intial condition is no l
# It is important to always have a breaking condition to stop the loop so it does
limit = 10
dept_size = 0
while dept_size < limit:
print(dept_size)
dept_size += 1

if dept_size == 8:
break # The 'break' statement in Python is used to close/end a loop

0
1
2
3
4
5
6
7

Lists
Collection of items in a particular order
They are used to store data and can be assigned to variables just like integers and strings
Indexing (order) starts from 0
Accessing items in a list can be done with square brackets ([ ])
Items can be easily added to lists using append() and insert() methods

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 6/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [18]: # Lists are a collection of data. List numberings always start from 0.

banks = ["RBC", "CIBC", "TD", "BMO"]


print(banks[0]) # Here the first item in the list is at index 0
print(banks[3]) # The third item in the list is at index 4

#Can use a colon to indicate range of indices


print(banks[0:3]) # From the first to third item
print(banks[:1])
print(banks[2:])

#Negative indexing goes from Right to Left, starting from -1


print(banks[-1])

#Reassign values with square brackets as well


banks[0] = "Scotiabank"
print(banks)

#Cannot do artists[4] = ""

RBC
BMO
['RBC', 'CIBC', 'TD']
['RBC']
['TD', 'BMO']
BMO
['Scotiabank', 'CIBC', 'TD', 'BMO']

In [19]: # add value to end of a list - Canadian Western Bank


# The .append() function can be used!
banks.append("CWB")
print(banks)

['Scotiabank', 'CIBC', 'TD', 'BMO', 'CWB']

In [20]: # add value to the start of a list - First Nations Bank of Canada
banks.insert(0, "FNBC")
print(banks)

# Return the length of the list


len(banks)

['FNBC', 'Scotiabank', 'CIBC', 'TD', 'BMO', 'CWB']

Out[20]: 6

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 7/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [21]: # Remove list entries


del banks[4]
print(banks)

['FNBC', 'Scotiabank', 'CIBC', 'TD', 'CWB']

Dictionaries
Collection of key-value pairs
No positions as with lists, values stored at specific key
keys can be of any data type
Accessing values in a dictionary can still be done with square brackets ([ ])
Declared using braces ({ })

In [22]: # collection of "data" which is unordered, changeable, and not indexed. They have
employee = { "name": "Peter", "employee_num": 314425, "workplace": "RBC"}
# Here, 'name', 'employee_num', and 'department' are keys, and 'Peter', '314425',
print(employee)

{'name': 'Peter', 'employee_num': 314425, 'workplace': 'RBC'}

In [23]: # Access key values using ['key_name']


employee["name"]

Out[23]: 'Peter'

In [24]: # Reassign a key value


employee["workplace"] = "TD"
print(employee["workplace"])

TD

In [25]: # Add a new key


employee["management"] = False
print(employee)

{'name': 'Peter', 'employee_num': 314425, 'workplace': 'TD', 'management': Fals


e}

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 8/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [26]: # Can remove a key easily using del


# Other keys are unaffected when you use 'del' to remove a key
del employee["management"]
print(employee)

{'name': 'Peter', 'employee_num': 314425, 'workplace': 'TD'}

In [27]: #Dictionary methods return iterables


print(employee.items())
print(employee.keys())
print(employee.values())

# Cannot do print(employee.keys[0]) because it is not a list


# Iterables are data objects that can be 'interated' over, like in loops
# Iterables to be used with keyword IN ('IN' example is covered in the next cell

dict_items([('name', 'Peter'), ('employee_num', 314425), ('workplace', 'TD')])


dict_keys(['name', 'employee_num', 'workplace'])
dict_values(['Peter', 314425, 'TD'])

In [28]: # You can use dictionaries and lists in 'if' statments.

#Will look through keys by default


if "name" in employee:
print("Yes, name is one of the keys in this dictionary")
else:
print("no")

Yes, name is one of the keys in this dictionary

For Loops
Execute a block of code once for each item in collection (List/Dictionary)
Declare temporary variable to iterate through collection
Can be used in combination with IF statements

In [29]: #Loop through banks list


for bank in banks:
print(bank)

FNBC
Scotiabank
CIBC
TD
CWB

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 9/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [30]: #Loop through pairs in employee dictionary


for key in employee:
print(key)

for key, value in employee.items():


print(f"{key}: {value}")

name
employee_num
workplace
name: Peter
employee_num: 314425
workplace: TD

In [31]: # Use RANGE to specify a number of iterations


for i in range(len(banks)): # The len() function returns the length of the previo
print(i)

0
1
2
3
4

In [32]: # Make a loop that prints all odd values from 1 to 21


for i in range(1,22,2):
print(i)

1
3
5
7
9
11
13
15
17
19
21

Functions
Named blocks of code that do one specific job
Functions are also referred to as methods
Prevents rewriting of code that accomplishes the same task
Keyword def used to declare functions
Variables may be passed to functions

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 10/12
1/21/2021 Class_1_Master - Jupyter Notebook

In [33]: # In this function 'name', 'employee_num', and 'department' are required values t
def description(name, employee_num, workplace):
print(f"{name} - Employee Number: {employee_num} - works at: {workplace}")

description("Mike", 12210, "CIBC")


description(employee['name'], employee['employee_num'], employee['workplace'])

Mike - Employee Number: 12210 - works at: CIBC


Peter - Employee Number: 314425 - works at: TD

Classes
NOTE: We cover classes in the next section, but here's a primer if you're interested
Object-orientated programming approach popular and efficient
Define classes of real-world things or situations (can be thought of as creating your own data
type)
Attributes of various data types
Functions inside of a class are the same except called methods
Methods may be accessed using the dot operator
Instanciate objects of your classes
__init()__ method used to prefill attributes
Capitalize class names

In [34]: class Employee():


"""A simple attempt to represent am employee."""
def __init__(self, name, employee_num, department ):
self.name = name
self.employee_num = employee_num
self.department = department

def description(self): # Creating a function (a.k.a method) that can be used


print(f"{self.name} (employee number: {self.employee_num}) - Dept: {self.

In [35]: employee1 = Employee("Mike", 12210, "Marketing")


employee2 = Employee("Peter", 31445, "IT")
employee1.description()
employee2.description()

Mike (employee number: 12210) - Dept: Marketing


Peter (employee number: 31445) - Dept: IT

User Input
localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 11/12
1/21/2021 Class_1_Master - Jupyter Notebook

OPTIONAL: Not covred during the bootcamp. Just some extra content if you're interested!
Pauses your program and waits for the user to enter some text
Variable used with Input() will be a string even if user inputs an integer
Will need to make use of type casting.

In [36]: #Ask user for a name


my_age = input("Enter your age.\n")
print(f"Entered age is {my_age}")
print(f"You were born in {2020 - int(my_age)}")

Enter your age.


22
Entered age is 22
You were born in 1998

Putting it all Together


This is an optional section - a great way to practice everything we've learned!
Note that to do this, you're expected to know both classes and input
Let's create a new Employee
We can then use our class methods easily!

In [37]: employee_input = input("Enter your name, employee number and department.\n")


name = employee_input.split(' ')[0]
employee_num = employee_input.split(' ')[1]
department = employee_input.split(' ')[2]
new_employee = Employee(name,employee_num,department)
new_employee.description()

Enter your name, employee number and department.


Seamus 3453243 Bootcamps
Seamus (employee number: 3453243) - Dept: Bootcamps

In [ ]:

localhost:8888/notebooks/BCHPython1/Python1/Class_1_Master.ipynb# 12/12

You might also like