Section 3: Python Object and Data Structure Basics

  Python Bootcamp 0 to Hero

Section 3 Menu

< Section 2
Section 4 >

  1. Introduction to Python Data Types
  2. Python Numbers
  3. Numbers FAQ
  4. Variable Assignments
  5. Introduction to Strings
  6. Indexing and slicing with Strings
  7. String Properties and Methods
  8. Strings FAQ
  9. Print Formatting with Strings
  10. Print Formatting FAQs
  11. Lists in Python
  12. Lists FAQ
  13. Dictionaries in Python
  14. Dictionaries FAQ
  15. Tuples with Python
  16. Sets in Python
  17. Booleans in Python
  18. I/O with Basic Files in Python
  19. Resources for More Basic Practice
  20. Python Objects and Data Structures Assessment Test Overviews
  21. Python Objects and Data Structures Assessment Test Solutions

 

My Comments

Coding Conventions

Ref ‘PEP8’: https://www.python.org/dev/peps/pep-0008/

Introduction to Python Data Types

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388518#content

Overview of the values


* Boolean type ‘None’ = null? It is the value returned if there is no return value….?

Python Numbers

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388520#content

  • % = Mod (Moulo) aka remainder
    • 7 % 4 = 3
    • 50 % 5 = 0
      • Good way to check if a value cleanly divides
      • Also good to check if a value is even or odd
        • 21 % 2 = 1
  • ** = Exponent
    • 2**3=8

Coding Exercise 1

Write an expression that = 100

10*10

Numbers FAQ

1. What’s the difference between floating point and an integer?

An integer has no decimals in it, a floating point number can display digits past the decimal point.

2. Why doesn’t 0.1+0.2-0.3 equal 0.0 ?

This has to do with floating point accuracy and computer’s abilities to represent numbers in memory. For a full breakdown, check out: https://docs.python.org/2/tutorial/floatingpoint.html

Variable Assignments

Naming Rules

  • Cannot start with a number
  • Cannot contain spaces
  • Cannot use any of the following characters:
    • : ‘ ” , < > / ? | \ ( ) ! @ # $ % ^ & * ~ – +
    • Best practice all variables are lower case
      • Exception is Global Variables which should be all CAPS
    • Avoid using variables that have special meanings, like list and str

Variable Typing

  • Python uses Dynamic Typing
    • You can reassign variable to different types:
      • my_var = 5
      • my_var = “hello”
  • Some other languages do not allow this
    • These are known as Statically Typed
    • Example for C++
      • int my_var = 5;
      • my_var = “hello”;
        • This results in an error!

Pros and Cons to Dynamic Typing

  • Pros
    • Very easy to work with
    • Faster development time
  • Cons
    • May result in bugs for unexpected data types
    • Need to be aware of type()

type()

  • a = 5
  • type(a)
    • int
  • a = 5.1
  • type(a)
    • float

Introduction to Strings

Indexing

  • Character: h e l l o
  • Index: 0 1 2 3 4
  • Reverse Index: 0 -4 -3 -2 -1
  • my_str = “hello”
    • my_str[1]
      • e
    • my_str[-1]
      • o

Slicing

  • Used to grab a sub-section of a string
  • [start:stop:step]
    • start = start index (Default = 0)
    • stop = up to, but not including this index (Default = len())
    • step = ‘jump’ size (Default = 1)

Indexing and slicing with Strings

  • ‘abcdefghijk'[2]
    • c
  • my_str = ‘abcdefghijk’
  • len(my_str)
    • 11
  • my_str[2]
    • c
  • my_str[-2]
    • j
  • my_str[2:] (no stop = all remaining characters)
    • cdefghijk
  • my_str[:3] (no start = start with 0)
    • abc
  • my_str[2:4]
    • cd
  • my_str[4:-5]
    • ef
  • my_str[::] (start at the beginning and go to the end)
    • abcdefghijk
  • my_str[::2]
    • acegik
  • my_str[::3]
    • adgj

Reversing a string

Note: When using a negative step size, the start and stop positions are also reversed

  • my_str[::-1] (Reverse a string)
    • kjihgfedcba
  • my_str[1::-1] (start = index 1, stop = through start of string, -1 = backwards)
    • ba
  • my_str[4:0:-1]
    • edcb
  • my_str[-2,7,-1]
    • ji

String Properties and Methods

Immutability

You cannot directly assign new values to string indexes

name = 'Sam'
name[0] = 'P'

TypeError: ‘str’ object does not support item assignment

Concatenation

Addition

Use a + symbol to concatenate (add together)

name = 'Sam'
pam = 'P' + name[1:]
print(pam)

Pam

Mutiplication

letter = 'z'
letter = letter * 5
print(letter)

zzzzz

Caution using Dynamic Types

2 + 3

5

'2' + '3'

23

String Objects and Methods

x = 'Hello World'
print(x.upper())
print(x)

HELLO WORLD
Hello World

x = 'Hello World'
x = x.upper()
print(x)

HELLO WORLD

x = 'Hello World'
print(x.lower())

hello world

Split

x = 'Hello World'
x.split()

[‘Hello’, ‘World’]

x = 'Hello World'
x.split('l')

[‘He’, ”, ‘o Wor’, ‘d’]

 

 

Strings FAQ

Print Formatting with Strings

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388532#content
Great resource: https://pyformat.info/

.format()

Strings

“String here {} then also {}”.format(var1, var2)

print('This is an {} string'.format('INSERTED'))

This is an INSERTED string

Indexing

print('The {2} {1} {0}'.format('fox', 'brown', 'quick'))

The quick brown fox

print('The {0} {0} {0}'.format('fox', 'brown', 'quick'))

The fox fox fox

Variables

print('The {q} {b} {f}'.format(f='fox', b='brown', q='quick'))

The quick brown fox

print('The {f} {f} {f}'.format(f='fox', b='brown', q='quick'))

The fox fox fox

Floating Point Numbers

value:.f

result = 100/777
print(result)
print("The result was {r:1.3f}".format(r=result)
print("The result was {r:10.3f}".format(r=result)

0.1287001287001287
The result was 0.129
The result was      0.129

Print(f” “)

husband = 'Thomas'
wife = 'Sofia'
print(f"{husband} is married to {wife}.")

Thomas is married to Sofia.

Print Formatting FAQs

https://www.udemy.com/complete-python-bootcamp/learn/lecture/3810438#content

Print Formatting FAQS

1.) I imported print from the __future__ module, now print isn’t working. What happened?

This is because once you import from the __future__ module in Python 2.7, a print statement will no longer work, and print must then use a print() function. Meaning that you must use

print(‘Whatever you were going to print’)

or if you are using some formatting:

print(‘This is a string with an {p}’.format(p=’insert’))

The __future__ module allows you to use Python3 functionality in a Python2 environment, but some functionality is overwritten (such as the print statement, or classic division when you import division).

Since we are using Jupyter Notebooks, once you so the import, all cells will require the use if the print() function. You will have to restart Python or start a new notebook to regain the old functionality back.

Lists in Python

Numerically indexed array containing a variety of values and objects.
* Lists are MUTABLE! You can change an index at will. (Unlike strings, which are immutable.)

husband = 'Thomas'
my_list=[husband, 53, 'String']
print(len(my_list))
print(my_list[0])

3
Thomas

Slicing and Indexing

Works EXACTLY the same as strings

husband = 'Thomas'
my_list=[husband, 53, 'String']
print(my_list[:2])

[‘Thomas’, 53]

Modifying Lists

Concatenate

list1 = ['one', 2, 'three']
list2 = ['4', 'Five']
list3 = list1 +  list2
print(list3)

[‘one’, 2, ‘three’, ‘4’, ‘Five’]

.append()

list3.append(6)
print(list3)

[‘one’, 2, ‘three’, ‘4’, ‘Five’, 6]

.pop()

Removes and returns an index from list. (Default = -1)

my_list = ['one', 2, 'three', '4', 'Five', 6]
print(my_list.pop())
print(my_list)

6
[‘one’, 2, ‘three’, ‘4’, ‘Five’]

my_list = ['one', 2, 'three', '4', 'Five', 6]
print(my_list.pop(1))
print(my_list)

2
[‘one’, ‘three’, ‘4’, ‘Five’, 6]

my_list = ['one', 2, 'three', '4', 'Five', 6]
print(my_list.pop(-2))
print(my_list)

five
[‘one’, ‘three’, ‘4’, 6]

Sorting

* Sorting is ‘in place’. That is:
It alters the actual array.
It does NOT return a value (None)

alpha = ['z', 'e', 'r', 't', 'm']
alpha.sort()
print(alpha)

[‘e’, ‘m’, ‘r’, ‘t’, ‘z’]

alpha = ['z', 'e', 'R', 't', 'm']
alpha.sort()
print(alpha)

[‘R’, ‘e’, ‘m’, ‘t’, ‘z’]

alpha = ['z', 'e', 'R', 't', 'm']
beta = alpha.sort()
print(beta)
type(beta)

NoneType

numlist = [3, 2, 0, 4, 1]
numlist.sort()
print(numlist)

[0, 1, 2, 3, 4]

.reverse()

numlist = [3, 2, 0, 4, 1]
numlist.reverse()
print(numlist)

[1, 4, 0, 2, 3]

Lists FAQ

1. How do I index a nested list? For example if I want to grab 2 from [1,1,[1,2]]?

You would just add another set of brackets for indexing the nested list, for example: my_list[2][1] . We’ll discover later on more nested objects and you will be quizzed on them later!

 

Dictionaries in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388536#content

Dictionaries are associative arrays, i.e. key:value pairs.

my_dict = {'key1':'value1', 'key1':2, 'key3':3.333, 'key4':[0, 1, 2]}

Dictionaries

  • Keys should always, but do not have to, be strings.
  • Grouped using curly brackets

Dictionaries vs Lists

  • Dictionaries
    • Objects retrieved by key name
    • These are unordered and cannot be sorted
  • Lists
    • Objects retrieved by location
    • Ordered sequence can be indexed or sliced.

Methods

.keys()

d = {'key1':1, 'key2':2, 'key3':'Three'}
print(d.keys())

dict_keys([‘key1’, ‘key2’, ‘key3’])

.values()

d = {'key1':1, 'key2':2, 'key3':'Three'}
print(d.values())

dict_values([1, 2, ‘Three’])

.items()

d = {'key1':1, 'key2':2, 'key3':'Three'}
print(d.items())

dict_items([(‘key1’, 1), (‘key2’, 2), (‘key3’, ‘Three’)])

  • Notice the return sets are in parenthesis.  These are Tuples!

Working with Objects

d={'key':['b','c','a']}
print(d['key'][2].upper())

A

d={'key':['b','c','a']}
d['key'].sort()
print(d['key'])

[‘a’, ‘b’, ‘c’]

 

Dictionaries FAQ

https://www.udemy.com/complete-python-bootcamp/learn/lecture/3729816#content

1. Do dictionaries keep an order? How do I print the values of the dictionary in order?

Dictionaries are mappings and do not retain order! If you do want the capabilities of a dictionary but you would like ordering as well, check out the ordereddict object lecture later on in the course!

Tuples with Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388540#content

  • Tuples use parenthesis: (1, 2, 3)
  • Similar to lists, but are immutable. Once an element is inside a tuple, it cannot be reassigned.
  • You can slice and index the same as a list but you cannot reorder!

Tuples are useful in advanced programming for passing objects when you must ensure the data integrity.

Immutability Example

t=('S', 'o', 'f', 'i','a')
t[2] = 'ph'

—————————————————————————
TypeError Traceback (most recent call last)
in
1 t=(‘S’, ‘o’, ‘f’, ‘i’,’a’)
—-> 2 t[2] = ‘ph’

TypeError: ‘tuple’ object does not support item assignment

Indexing and Slicing example

t=('S', 'o', 'f', 'i','a')
t[1:4]

(‘o’, ‘f’, ‘i’)

Methods

.count()

Counts the number of occurrences of a value in the tuple.

t = ('a', 'b', 'a', 'c')
t.count('a')

2

.index()

Returns the first index occurrance of a value

t = ('a', 'b', 'a', 'c')
t.index('a')

0

 

Sets in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388544#content

  • Sets are unordered collections of unique elements
    • There are no indexes
  • There can only be one representative of the same object
    • Each value in the set must be unique.  There are no duplucates

Set Example

myset = set()
myset

set()

myset.add(1)
myset

{1}

myset.add(2)
myset

{1, 2}

myset.add(2)
myset

{1, 2}

Usage

mylist = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4]
set(mylist)

{1, 2, 3, 4}

set('Mississippi')

{‘M’, ‘i’, ‘p’, ‘s’}
* Notice the values are NOT in the order they are in the array!

Booleans in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388546#content

    • True or False
    • Also allows ‘None’
      • Used to defined ‘undefined’ variables
    • First letter MUST be capitalized, otherwise it is a variable.

True and False examples

1 > 2

False

1 == 1

True

None examples

x

NameError: name ‘x’ is not defined

x = None

(Nothing displayed)
18% Complete

I/O with Basic Files in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9388552?start=30#content

Setup

Note:

Get the current working directory of your Jupyter Notebook using the ‘pwd’ command

pwd

‘C:\\Users\\user1\\path\\to\\jupyter\\notebook’

Create a text file with a few lines in it.  In Jupyter Notebooks, use the following:

%%writefile myfile.txt
Hello this is a text file.
This is the second line
and this is on the third line

Writing myfile.txt

Open the file

myfile = open('myfile.txt')

Methods

.read()

myfile.read()

‘Hello this is a text file.\nThis is the second line\nand this is on the third line’
This method sets the read location to the end of the file. Trying to read again results in an empty string

myfile.read()


See .seek() below.

.seek()

Sets the read position and returns that value

myfile.seek(0)

0

myfile.seek(0)
myfile.read()

‘Hello this is a text file.\nThis is the second line\nand this is on the third line’

myfile.seek(4)
myfile.read()

‘o this is a text file.\nThis is the second line\nand this is on the third line’

.readlines()

myfile.seek(0)
myfile.readlines()

[‘Hello this is a text file.\n’,
‘This is the second line\n’,
‘and this is on the third line’]

<h2>File Locations</h2>

If you want to open files at another location on your computer, simply pass in the entire file path.

Windows

You will need to use a double backslash ‘\\’ to prevent Pyton from reading it as an escape character

myfile = open("C:\\Users\\user1\\path\\to\\folder\\myfile.txt")

Mac and Linux

Use slashes as you normally do.

myfile = open("/home/user1/path/to/folder/myfile.txt")

Closing Files

It is IMPORTANT that you remember to close the file! Failure to do so will leave the file open and others will not be able to alter it.

.close()

myfile.close()

with / as

with open('myfile.txt' as my_new_file:
    contents = my_newe_file.read()
contents.read()

‘Hello this is a text file.\nThis is the second line\nand this is on the third line’
This method closes the file as soon as the ‘ny_new_file’ object is created

Writing to a file

with open('myfile.txt, mode='w') as myfile:
    contents = myfile.read()

UnsupporedOperation: not readable
* the file was ONLY opened for WRITE mode!

Understanding mode=

  • mode=’r’ – read only
  • mode=’w’ – write only (will overwrite files or create new!)
  • mode=’a’ – append (will add on to files)
  • mode=’r+’ – reading and writing
  • mode=’w+’ – reading and writing (overwrites existing files or creates a new file)

Create a new file

%%writefile my_new_file.txt
ONE ON FIRST
TWO ON SECOND
THREE ON THIRD

Writing my_new_file.txt

mode=’r’

with open('my_new_file.txt', mode='r') as f:
    print(f.read())

ONE ON FIRST
TWO ON SECOND
THREE ON THIRD

mode=’a’

with open('my_new_file.txt', mode='a') as f:
    f.write('\nFOUR ON FORTH'))
with open('my_new_file.txt', mode='r') as f:
    print(f.read())

ONE ON FIRST
TWO ON SECOND
THREE ON THIRD
FOUR ON FORTH

Resources for More Basic Practice

Before you begin your assessment, I wanted to point out some helpful links for practice (don’t worry about being able to do these exercises, I just want you to be aware of the links so you can visit them later, since we still haven’t discussed functions, you won’t be able to utilize a lot of these resources yet!):

Basic Practice:

http://codingbat.com/python

More Mathematical (and Harder) Practice:

https://projecteuler.net/archives

List of Practice Problems:

http://www.codeabbey.com/index/task_list

A SubReddit Devoted to Daily Practice Problems:

https://www.reddit.com/r/dailyprogrammer

A very tricky website with very few hints and touch problems (Not for beginners but still interesting)

http://www.pythonchallenge.com/

Course 20% Complete

Python Objects and Data Structures Assessment Test Overviews

 

Python Objects and Data Structures Assessment Test Solutions

 

LEAVE A COMMENT