Python Review Questions The following questions are meant to help you review introductory concepts in Python. They are based on the Python 3 Tutorial and Python 3 Documentation and were written to accompany a 5 lecture series on Python.
There are three types of questions:
Verify the Code: Determine the output of a code snippet. Fill in the Code: Fill in the code to complete a code snippet. Create the Function: Create a function that satisfies the given requirements. Verify the Code Operations on Strings
NumPy Quickstart This notebook is a quick introduction to NumPy. It is an interactive version of the NumPy Quickstart Tutorial.
All credits go to the original authors of the tutorial © Copyright 2008-2023, NumPy Developers.
The Basics NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
NumPy Quickstart This notebook is a quick introduction to NumPy. It is an interactive version of the NumPy Quickstart Tutorial.
All credits go to the original authors of the tutorial © Copyright 2008-2023, NumPy Developers.
Copies and Views When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases:
# `NumPy` Quickstart This notebook is a quick introduction to NumPy. It is an interactive version of the NumPy Quickstart Tutorial.
All credits go to the original authors of the tutorial © Copyright 2008-2023, NumPy Developers.
Shape Manipulation Changing the shape of an array An array has a shape given by the number of elements along each axis:
import numpy as np a = np.floor(10 * np.random.random((3,4))) print("a = \n{}".format(a)) print("a.shape = {}".format(a.shape)) a = [[6. 7. 2. 1.] [5. 9. 4. 9.] [3. 5. 3. 2.]] a.shape = (3, 4) The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array:
Loading Data for ML Applications In this notebook, we will implement code to load data for ML applications. Following the approach used by PyTorch, we will implement a Dataset class and a DataLoader class. The Dataset class will be used to load the data and the DataLoader class will be used to iterate over the data in batches.
We will test it on a simple image dataset.
The Dataset Class First, we need some way of representing how each individual item will be pre-processed as the dataloader iterates over the data. We will do this by creating a Dataset class. Since this class represents multiple items in our dataset, we will need to define the following special methods:
Classes When a class is defined, a namespace is created for it. All assignments to local variables are part of this namespace. The code below defines a class, creates an instance of the class, and calls a method on the instance.
class Shape(): """Represents any shape.""" def __init__(self, color): self.color = color self.orientation = 0.0 def rotate(self, angle): self.orientation += angle s = Shape("red") s.rotate(45.0) print(s.orientation) 45.0 Class and Instance Variables The class above has two instance variables, color and orientation. These variables are accessed using the self keyword. The self keyword is used to access instance variables and methods.
File I/O in Python This notebook will cover the following topics:
Opening and closing files Reading and writing text files Reading and writing binary files Using the with statement Using the pickle module Serializing objects with pickle Reading and writing JSON files Opening and closing files Let’s start with the basics. To open a file, we use the built-in open() function. The open() function takes two arguments: the name of the file to open and the mode in which to open it. The mode can be one of the following:
Functions We learned the importance of functions early on in mathematics. It is a compact way of represented a complex process dependent on a set of variables. In programming, functions are used to encapsulate a set of instructions that are used repeatedly. Functions are also used to make code more readable and easier to debug.
In this notebook, we will look at a few important built-in functions in Python as well as how to define our own functions.
Lists and List Comprehensions List comprehensions provide a concise way to create lists, and are often faster than using a for-loop. They are inspired by set-builder notation in mathematics.
This notebook demonstrates common list functions as well as the syntax and basic usage of list comprehensions.
names = ["Naomi", "James", "Amos", "Bobbie"] # Append "Miller" to the end of the list names.append("Miller") # This can also be accomplished using the + operator or the extend() method # These are similar, where `+=` is shorthand for `extend` names.extend(["Chrisjen"]) names += ["Alex"] # `extend()` works on any iterable names.extend(["Fred", "Dawes", "Ashford"]) # This can also be done using slicing # names[len(names):] = ["Fred", "Dawes", "Ashford"] # Insert "Holden" at the beginning of the list names.insert(0, "Holden") # We can easily remove items names.remove("Alex") # We can also remove items by value names.remove("Ashford") # We can also remove items by index. This will return the removed item eros_passenger = names.pop(5) print(eros_passenger + " is on his way to Venus") # If your list has duplicates, you can count the number of times a value appears print("Naomi" + " appears " + str(names.count("Naomi")) + " time(s)") # Reversing a list is easy names.reverse() # We can also create a shallow copy of a list names_copy = names.copy() Miller is on his way to Venus Naomi appears 1 time(s) Sorting A list can be sorted by calling the sort function. The list is sorted in-place, meaning that the original list is modified. Since a list can contain any type of object, the objects must be comparable to each other. For example, a list of strings can be sorted alphabetically, but a list of strings and integers cannot be sorted.
Control Flow Control flow allows us to build programs that react to some pre-determined condition. For example, what happens when a user logs in with the correct credentials? What if they don’t give valid credentials?
This notebook covers the basic tools to writing conditional statements in Python. It follows Chapter 3 in Python for Everyone by Charles Severance along with my own examples.
Boolean Expressions A boolean expression evaluates to either True or False. This type of expression would be used to check status codes or to check if a user has entered the correct password, for example.
Table of Contents Introduction Programming with Python Variables, Values, and Data Types Basic Operators Statements and Expressions Basic I/O Commenting Code These notes are focused on introducing programming with Python for those without a technical background.
Introduction The official website provides the following description of Python.
Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. It supports multiple programming paradigms beyond object-oriented programming, such as procedural and functional programming. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants including Linux and macOS, and on Windows.