Skip to content
Snippets Groups Projects
Commit 27ba2078 authored by Colbry, Dirk's avatar Colbry, Dirk
Browse files

Merge branch 'SuliahBranch' into 'main'

Basic Containers and Functions

See merge request !6
parents 2ccda9da dc116276
No related branches found
No related tags found
1 merge request!6Basic Containers and Functions
%% Cell type:markdown id:3c2a4f39 tags:
# Basic Containers
Understanding and Using Basic Containers in Python
%% Cell type:markdown id:2b78245b tags:
![Google Python Symbol- Image found in the public domain](https://freesvg.org/img/387.png)
https://freesvg.org/img/387.png
Python Language Logo from Free SVG
%% Cell type:markdown id:71e867d9 tags:
## Description
Many times, in using python, there will be a need to store values. A common way to do so and store the values under a single variable is to use basic containers. This page will breakdown the common container types in Python.
%% Cell type:markdown id:58ec20e8 tags:
## Self Assessment
Click the following link to assess your knowledge on Basic Containers:
https://realpython.com/quizzes/pybasics-tuples-lists-dicts/
%% Cell type:markdown id:5d237ca9 tags:
## Training Materials
%% Cell type:markdown id:21f9b14e tags:
Video Description (URL Link to video)
%% Cell type:code id:deeec8f7 tags:
``` python
from IPython.display import YouTubeVideo
YouTubeVideo("aBqTgR-gP3g",width="100%", height=360, cc_load_policy=True)
```
%% Output
<IPython.lib.display.YouTubeVideo at 0x1cd12db60d0>
%% Cell type:raw id:08e8ef5c tags:
|Container Type|Mutable or Immutable|Initialization *Without* Values|Initializtion *With* Values|Adding Values to Container|Removing Values from Container|Modifying Values|Access Method|Notable Operations and Additional Information|
|---|---|---|---|---|---|---|---|---|
|**List**| Mutable |<ul><li>`a=list()` </li><li> `a=[]` </li></ul> | `a=['1', '2', '3']`| <ul><li>` list.append(item) #Adds item to the end of the list` </li><li> ` list.insert(index, item) #Adds item to the specified index in the list`</li></ul>|`list.remove(item) #removes the first instance of 'item' from the list. If there is not such element, this will cause an error`|`>>> a[0] = 'cat'` <br> `>>> a` <br> `['cat', '2', '3']` |Access by index: <br> `>>> a[0]` <br> `1`|See webpage at http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch14s07.html for some helpful methods when dealing with lists.|
|**Dictionary**|Mutable| `student={}` | `>>> student={'name': 'John Doe', 'age': 22, 'college': 'MSU'}` | `>>> student['major']='Computer Science'` <br> `>>> student` <br> `{'name': 'John Doe', 'age': 22, 'college': 'MSU', 'major': 'Computer Science'}` | `del dictName[keyName] #This method removes all entries associated with the given key` | `>>> student['age'] = 23` <br> `>>> student` <br> `{'name': 'John Doe', 'age': 23, 'college': 'MSU', 'major': 'Computer Science'}`| Access by key word. Note that this key **must** be a string. <br> `>>>student['college']` <br> `MSU`| The 'in' keyword can be very helpful with dictionaries. Ex: <br><ul><li>`'k' in dict #Returns true if key 'k' is in dictionary dict`</li><li>`'k' not in dict #Returns true if key 'k' is not in dicitonary dict`</li><li>`for key in dict #This will iterate over all keys in dictionary dict`</li></ul> <br>See webpage at http://www.python-course.eu/python3_dictionaries.php for additional helpful methods and operations|
|**Set**|Mutable. However the objects contained within a set **must** be immutable. | `s=set()`|`s=set(['a','b','c'])` | `s.add(item)`|<ul><li> `set.discard(item) #If item is in the set, the item is removed, otherwise nothing happens` </li><li> `set.remove(item) #If item is in the set, the item is removed, otherwise raise a KeyError` </li><li> `set.pop() #Remove and return an arbitrary element from the set. If the set is empty, raise a KeyError` </li>| Sets are unordered, therefore indexing does not mean anything. To modify a set, you must directly add or remove elements. |`>>> set.pop() #This will remove and return an arbitrary element from the set`|Some helpful methods include:<ul><li>`difference()`</li><li>`intersection()`</li><li>`isdisjoint()`</li><li>`union()`</li></ul><br> See webpage at http://www.programiz.com/python-programming/set for additional helpful methods and operations|
| **Tuple** |Immutable|<ul><li>`t=()`</li><li> `t=tuple()`</li><ul>|<ul><li>1-tuple:<br>`t=('Hello',)`</li><li> 2-tuple:<br> `t=('Hello', 'Goodbye')`</li><ul>|N/A|N/A|N/A|`t=('Hello','Goodbye','Goodnight')`<ul><li>Access By Index: <br> `>>> t[0]` <br> `'Hello'` </li><br><li> Access By Slice <br> `>>>t[0:1:2]` <br> `('Hello','Goodbye')`</li></ul>|<ul><li>Packing and Unpacking</li><br><li>Tuple to List: `list(tupleName)`</li></ul>|
| **NumPy Array\***|Mutable|`a=np.array([])`| `a=np.array([1,2,3,4,5])` | <ul><li>`np.insert(arrayName,index,values,axis) #Inserts a value for an array at the given index.` </li><li>`np.append(arrayName,value,axis) #Appends values to the end of an array.`</li></ul>|`np.array(array,index/indices,axis) #Returns a new array with the given index or array of indices deleted on the given axis`|`>>> a[4] = 12` <br> `array([ 1, 2, 3, 4, 12])` <br><br> For additional information on manipulating NumPy Arrays see the webpage at http://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html |<ul><li>Access By Index: <br> `>>> a[0] `<br>` 1 `</li><li>Access By Slice: <br> `>>> a[0:5:2] `<br> `array([1, 3, 5])` </li></ul><br>See webpage at http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html for further information about indexing of NumPy Arrays|See webpages at http://www.scipy-lectures.org/intro/numpy/array_object.html and https://docs.scipy.org/doc/numpy-dev/user/quickstart.html for additional information on NumPy Arrays|
\*Use of the NumPy Array requires the NumPy Python Module. Assuming import statement is "import numpy as np"
%% Cell type:markdown id:8bdbe577 tags:
List – a data structure in Python that is a mutable ordered sequence of elements.
my_list = [1, “world”, 5.9]
Dictionary – a mutable data storage method which is used to store data values in key : value pairs.
my_dict = {‘msu’: 1, ‘spartans’ : ‘green’, “mcdonel’ : ‘hall’}
Tuple – used to store multiple items in a single variable.
my_tuple = (“apple”. “bananas”, “cherry”, “strawberry”)
NumPy Array – a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers.
import numpy as np
arr = np.array(1, 2, 3, 4, 5, 6)
print(arr)
output: [1, 2, 3, 4, 5, 6]
Array – a collection of items stored at contiguous memory locations. Values can be accessed by referring to an index number.
cars = [“bmw”, “jeep”, “toyota”, “kia”]
Map – a built-in function that allows the user to process and transform all the items in a container in an iterable(such as a list or dictionary without using a loop.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
output: [2, 4, 6, 8]
%% Cell type:markdown id:44b461a0 tags:
---
Written by Suliah Apatira, Michigan State University
As part of the Data Science Bridge Project
<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International License</a>.
%% Cell type:markdown id:3c2a4f39 tags:
# Functions in Python
An Introduction to Creating and Using Functions in Python
%% Cell type:markdown id:2b78245b tags:
![Coding in Python Screen - Image found in the public domain](https://live.staticflickr.com/822/40238552784_c48d2029a2_b.jpg)
Coding [Day 102] photo found on Flickr by gerlos
%% Cell type:markdown id:71e867d9 tags:
## Description
The fundamental units of any Python program are functions. A function is a named segment of code with a name that carries out a specific action. Usually, this entails receiving some input, processing it, and then producing an output. Functions let you divide your code into distinct, reusable pieces. Functions can even be used outside of the original application in which they were defined. There are two types of functions called built-in functions and user-defined functions. Built-in functions are built into Python. Whereas, user-defined functions are defined by the users themselves.
%% Cell type:markdown id:58ec20e8 tags:
## Self Assessment
1. Python Functions Quiz: Python Functions Quiz https://pynative.com/python-functions-quiz/
2. Python Functions Exercise: https://pynative.com/python-functions-exercise-with-solutions/
3. Python Basics: Chapter 06 – Functions and Loops Quiz:
https://realpython.com/quizzes/pybasics-functions-loops/
It is suggested that you are familiar with loops and functions before completing this quiz. There is a crash course on loops in training material #2.
%% Cell type:markdown id:5d237ca9 tags:
## Training Materials
%% Cell type:markdown id:21f9b14e tags:
1. In this article, you'll learn about functions, what a function is, the syntax, components, and types of functions. Also, you'll learn to create a function in Python.
https://www.programiz.com/python-programming/function#:~:text=In%20Python%2C%20a%20function%20is,and%20makes%20the%20code%20reusable
%% Cell type:markdown id:ebf1e694 tags:
2. In this 12 minute video, you'll get a crash course into statements & functions.
%% Cell type:code id:ee42a54e tags:
``` python
from IPython.display import YouTubeVideo
YouTubeVideo("l26oaHV7D40",width="100%", height=360, cc_load_policy=True)
```
%% Output
<IPython.lib.display.YouTubeVideo at 0x1c4b55e6c10>
%% Cell type:markdown id:dd9c7fa5 tags:
3. If you need more indepth help, this 30 minute video has a step-by-step breakdown of how to create and use functions in python.
%% Cell type:code id:64684dfd tags:
``` python
from IPython.display import YouTubeVideo
YouTubeVideo("u-OmVr_fT4s",width="100%", height=360, cc_load_policy=True)
```
%% Output
<IPython.lib.display.YouTubeVideo at 0x1c4b55cc040>
%% Cell type:markdown id:44b461a0 tags:
---
Written by Suliah Apatira, Michigan State University
As part of the Data Science Bridge Project
<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International License</a>.
%% Cell type:code id:116d24a5 tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment