Introduction to Python – Data Structures (Input and Output)

Categories Devnet, Python
  • You can format the data that is output from python. The data can be returned as human readable output, the data can be returned to a file to be used later. This can be done through expression statements, the print() function or using the write() method for file objects.

Oh, you Fancy! huh?

  • Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.
  • Formatted string literals, also known as f-strings allow you to include the value of an expression inside a string. The format is to start with an f or F before the string and adding curles to the expression ie: {expression}
  • An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:
  • Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.
  • There are many other formats you can use on literal strings.

String() Format Method()

  • The str.format() method works as follows:

Introduction to Python – Modules

Categories Python, Windows

You can follow along with the code at Github.

  • A module in Python allows you to put definitions in a file and use them in a script or in an interactive instance of the interpreter.
  • Definitions from a module can be imported into other modules or into the main module.
  • I have created a module named fibMod.py which we will import into the interpreter and Visual Studio Code.
  • The module must be in the same path or have the path specified for it to be imported.
  • NOTE: You can import modules in the interpreter.
  • Example of importing the module using VS Code.

Introduction to Python – Data Structures (Dictionaries)

Categories Python

You can follow along with the code from Github.

Dict

  • The main operations on a dictionary (dict) are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
  • Keys can be any immutable type – strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples. If a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

Looping Techniques

You can follow along with the code flow from the Github.

  • You can use different techniques when looping through dictionaries.

items() method – The key and corresponding value can be retrieved at the same time.

  • enumerate() method – position index and corresponding value can be retrieved at the same time when looping through a sequence.
  • zip() method – To loop over two or more sequences at the same time.
  • reversed() method – loop over a sequence in reverse, first specify the sequence in a forward direction
  • sorted() method – loop over a sequence in a sorted order which returns a new sorted list while leaving the source unaltered.
  • set() method – Eliminates duplicate elements on a sequence. Set() can be using with sorted() method to loop over unique elements of the sequence in the sorted order.

Introduction to Python – Data Structures (Sets)

Categories Python

You can follow along with the code using Github.

  • A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
  • Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Introduction to Python – Data Structures (Tuples)

Categories Python

You can follow along with the code from Github.

  • A tuple consists of a number of values separated by commas.

Tuple Packing and Unpacking

  • In Python we can pack the tuple by putting values into a new tuple
  • Unpacking a tuple is when we extract its values into a single variable.

List Vs Tuples

  • Lists are mutable – They can be changed or modified after creation according to the developers needs.
  • Tuples are immutable – they can’t be changed or modified after creation.
  • List have more operations (functions) available to them.
  • Syntax is different
  • A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

Introduction to Python – Data Structures (Lists)

Categories Python
  • Data structures are used to store a collection of related data. There are four built-in data structures in Python – list, tuple, dictionary and set.
  • ***NOTE: It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.***

Lists as Stacks

  • The last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.

Lists as Queues

  • The first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
  • To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends.
  • Notice the queues only can pop from left to right.

List Comprehensions

  • <+Make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
  • Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects.
  • A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal.
  • Notice that the order of the for and in statements are in the same order in both of the examples.

Methods for List Objects

  • append – Used to add an object to the end of a list.
    ***Notice append will only take one argument at a time.***
  • extend – Extends a list by adding all items from the iterable.
    ***Notice the difference between append and extend.***
  • insert – Inserts the object into a list at a given index. (0 = beginning of the list)
  • remove – Removes an object from a list. You must specify the object to be removed. If it is a string you must specify the sting.

Clear – Clears all objects out of a list.

  • index – locate and search for an object within the list starting at a given index.

Introduction to Python – Function Arguments

Categories Python

https://github.com/rfc-1925/Python

  • An argument (also known as an arg) is data that can be push into a function.
  • The function must be called with the exact number of arguments that it is expecting. Notice the error received.
  • The code also uses the ‘in’ keyword. This keyword tests whether or not a sequence contains a specific value. The values are evaluated at the function definition within the defining scope.
  • Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. One can think of the keyword arguments (kwargs) as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
  • The form is kwarg=value
  • Now notice when we call the function with the proper number of arguments we no longer receive the error.
  • ***The reason we are not having to pass the ‘reminder’ argument is explained next.***

Default Arguments

  • Default arguments are used so that a function can be called with fewer arguments than it is defined to allow.
  • In the past example we needed to pass the argument ‘retries’ or else we would receive an error.
  • Now if we change our default value the number of times the function iterates is different. Why?
  • Notice that the default value is evaluated only once.
  • when the default is a mutable object such as a list, dictionary, or instances of most classes the function accumulates the arguments passed to it on subsequent calls.

Github – Create a Repository and Push Your Code with Git

Categories Git, Github, Linux, Python
  • Create a repository name and give it a description.
  • Set the repository for public view or private where you can control who sees the repository.
  • You can select to auto generate a README file for general information about the repository.
  • You can choose to add a .gitignore which will omit tracking.
  • You can also give permissions VIA licensing.
  • Once the repository is created you can hop over to the terminal and follow the same syntax to initialize and push your files to the Github repository.
  • After a successful push you will now be able to see the content inside of the Github repository.

A Few Benefits

  • Easier project contribution
  • Version control
  • A showcase for your work

Introduction to Python – Control Flow

Categories Python

If Statement

For Statement

  • Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

Range Function

  • Iterating over a sequence of numbers

Break Statement

Breaks out of the innermost loop.

  • Loop statements may have an else clause.
  • Using for or when the condition becomes false with while, but not when the loop is terminated by a break statement.

Continue Statement

Pass Statement

  • The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
  • It can also be used as a placeholder for a future class definition.

Defining Functions

  • A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function.