Python Flashcards

1
Q

Boolean Values?

A

Assesses the truth value of something. It has only two values: True and False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what are tuples?

A

A type of data that is immutable (can’t be modified after its creation) and can hold a group of values. Tuples can contain mixed data types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what are Lists?

A

A type of data that is mutable and can hold a group of values. Usually meant to store a collection of related data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what are Dictionaries?

A

A group of key-value pairs. Dictionary elements are indexed by unique keys which are used to access values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

One of the most important aspects of Python is….

A

indentation. Python has no brackets, braces, or keywords to indicate the start and end of certain code blocks such as functions, if statements, and loops. The only delimiter is the colon (:) and the indentation of the code itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

While loops are often used when…

A
we don't know how many times we have to repeat a block of code but we know we have to do it until a certain condition is met.
For loop example:
for count in range(0,5):
    print("looping - ", count)
While loop comparison of above:
count = 0
while count < 5: # notice the colon!
    print("looping - ", count)
    count += 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the break statement do?

A

exits the current loop prematurely, resuming execution at the first post-loop statement, just like the traditional break found in C or JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the continue statement do?

A

returns the control to the beginning of the loop. The continue statement rejects – or skips – all the remaining statements in the current iteration of the loop, and continues normal execution at the top of the loop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the pass statement do?

A

is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is almost never seen in final production, but can be useful in places where your code has not been completed yet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
What are the comparison and logic operators for:
is equal
is not equal
greater than
less than
greater than or equal
less than or equal
and
or
not
A
==
!=
>
<
>=
<=
and
or not
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a function?

A

a named block of code that we can execute to perform a specific task.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you define a function?

A
def add(a,b):
x= a+b
return x
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
What does 
def add(a,b):
x= a+b
return x
do?
A

it defines the function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you invoke a function?

A

by using the () after the function name. eg:

add(8,9)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What’s the difference between a parameter and an argument?

A
in the following example:
def add(a,b):
x= a+b
return x
add(8,9)

a and b are the parameters and 8 and 9 are arguments. We define parameters. We pass in arguments into functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Why is it important to return a value in a function?

A

So we can use the returned value later in our program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are common string methods?

A

string.upper()
string.lower()
string.count(substring) returns the # of occurences
string.split(char) splits the string by default at every space or at specified delimiter
string.isalnum() returns boolean depending on whether the string’s length is > 0 and all characters are alphanumeric. Strings that contain anything other than alphanumeric characrers return False
similar methods include .isalpha(), isdigit()
string.join(list) returns a string that is concatenated
string.endswith(substring) returns a boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are built-in functions for lists and tuples?

A

max(sequence) returns the largest value in the sequence
sum(sequence) return the sum of all values in sequence
map(function, sequence) applies the function to every item in the sequence you pass in. Returns a list of the results.
min(sequence) returns the lowest value in a sequence.
sorted(sequence) returns a sorted sequence

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are built-in functions and methods for dictionaries?

A

Python includes the following standalone functions for dictionaries:

len() - give the total length of the dictionary.
str() - produces a string representation of a dictionary.
type() - returns the type of the passed variable. If passed variable is a dictionary, it will then return a dictionary type.
Python includes the following dictionary methods (either dict.method(yourDictionary) or yourDictionary.method() will work):

.clear() - removes all elements from the dictionary
.copy() - returns a shallow copy dictionary
.fromkeys(sequence, [value]) - create a new dictionary with keys from sequence and values set to value.
.get(key, default=None) - for key key, returns value or default if key is not in dictionary.
.items() - returns a view object of dictionary’s (key, value) tuple pairs.
.keys() - return a view object of dictionary keys.
.pop(key) - returns the value associated with the key and removes the key-value pair from the dictionary.
.setdefault(key, default=None) - similar to get(), but will set dict[key]=default if key is not already in dictionary.
.update(dict2) - adds dictionary dict2’s key-values pairs to an existing dictionary.
.values() - returns a view object of dictionary values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is an anonymous function?

A

a function without a name. They are created with the lambda keyword. They are good for:
~when we need to use the function once
~when we need to break down complex tasks into small, specific task
~convenient as arguments to functions that require functions as parameters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Give an example of a lambda functions.

A
def square(num):
    x = num ** 2
    return x
lambda method:
def square(num):
lambda num: num ** 2 or
lambda num1, num2: num1+num2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Use a lambda to create an element in a list

A
# create a new list, with a lambda as an element
my_list = ['test_string', 99, lambda x : x ** 2]
# access the value in the list
print(my_list[2]) # will print a lambda object stored in memory
# invoke the lambda function, passing in 5 as the argument
my_list[2](5)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Pass a lambda to another function as a callback

A
# define a function that takes one input that is a function
def invoker(callback):
    # invoke the input pass the argument 2
    print(callback(2))
invoker(lambda x: 2 * x)
invoker(lambda y: 5 + y)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Store a lambda in a variable.

A

add10 = lambda x: x + 10 # store lambda expression in a variable
add10(2) # returns 12
add10(98) # returns 108

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Return a lambda by another function.

A
def incrementor(num):
    start = num
    return lambda x: num + x
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is a closure function?

A
A function object that remembers values in enclosing scopes even if they are not present in memory. eg:
# Python program to illustrate
# closures
def outerFunction(text):
    text = text
    def innerFunction():
        print(text)
return innerFunction # Note we are returning function WITHOUT parenthesis
if \_\_name\_\_ == '\_\_main\_\_':
    myFunction = outerFunction('Hey!')
    myFunction()
Run on IDE
Output:
Hey!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is a Python module?

A

Python files with the .py extension which implement a set of functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

How do we bring modules into our code?

A

Modules are imported using the import command.

import arithmetic

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do we make our own modules?

A

To create a module, we first create a new .py file with the module name in the same directory as the file that will import the module. Then we import it using the import command and the Python file name (without the .py extension)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is a Python package?

A

a collection of modules in directories that give a package hierarchy.
from my_package.subdirectory import my_functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is the purpose of having a file called __init__.py in a directory?

A

Each package in Python is a folder which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory containing it is a Python package, so it can be imported the same way a module can be imported.

The __init__.py file can also decide which modules this package will export as an API, while keeping other modules internal, by overriding the __all__ variable, like so:

#file \_\_init\_\_.py:
\_\_all\_\_ = ["test_module"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is OOP?

A

It allows us to create a blueprint for the purpose of reproducing objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What does instantiate mean?

A

Once we’ve created a blueprint for an object, we have to create an instance of the object. In other words create the object using the blueprint provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is class?

A
It is how we define our blueprint and are instructions on how to build many objects that share characteristics.
class User:
    pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How do we instantiate our blueprint class User: pass?

A

michael = User()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What two things do classes include?

A

Attributes: Characteristics shared by all instances of the class type. Think about what we want to know about our users, for example. We may decide that all users should have a name and an email. We’ll show you how to handle this in the next module.

Methods: Actions that an object can perform. A user, for example, might be able to make a purchase. A method is like a function that belongs to a class. It’s some instructions that will only work when called on an object that has been created from that class. We’ll show you how shortly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Objects can store 2 different types of information. What are they?

A

Attributes are characteristics of an object while methods are things an object can do. eg:

class User:
    # the \_\_init\_\_ method is called every time a new object is created
    def \_\_init\_\_(self, name, email):
        # the following are the object's attributes
        self.name = name
        self.email = email
        self.logged = False
    # this is a method we created to help a user login
    def login(self):
        self.logged = True
        print(self.name + " is logged in.")
        return self
#now create an instance of the class
new_user = User("Anna","anna@anna.com")
print(new_user.email)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is the __init__() method and when is it called?

A

It is called every time a new object is created. Python’s __init__() method is something that’s known as a magic method. Magic methods are automatically created and sometimes invoked when a new instance of a class is created. __init__() is useful because it allows us to set some attributes when a new instance is created. Because we know that the __init__() method will run immediately, we can pass in some arguments to that __init__() method upon object creation. We do not have to explicitly call this method. All we do is create our instance and provide the arguments we like, and the rest is done for us. The arguments we provide will be passed on to the __init__() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is an object or instance?

A

A data type built according to specifications provided by the class definition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is an attribute?

A

A value. Think of an attribute as a variable that is stored within an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is a method?

A

A set of instructions. Methods are functions that are associated with an object. Any function included in the parent class definition can be called by an object of that class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What does the self parameter do?

A

The self parameter includes all the information about the individual object that has called the method. Without self, every time we changed one object’s attributes, we’d change the attribute for all the items of that type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is the benefit of being able to chain methods?

A

It avoids DRY. eg:

user1.login().show().logout()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

If we wanted to define a new class we would start with which line

A

class ClassName:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How can we set attributes to an instance of a class

A

Initializing our attributes with the __init__() function

We can set individual attributes to each instance - one by one

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

The __init__() function gets called while the object is being constructed?

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Can you define an __init__() function that has parameters?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

How do you pass arguments to the __init__() function?

A

When creating an object instance you pass the arguments to the specified class you are creating an instance of

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What is the purpose of an __init__() function?

A

To prevent you from rewriting the same code each time you create a new object
To set properties required to execute certain instance methods as soon as the object is instantiated
To execute whatever logic we want to for each object that is created

50
Q

A constructor function cannot call any other methods inside the class.

A

False

51
Q

What is inheritance in the context of OOP and what are its benefits?

A

is forming new classes using classes that have already been defined. In other words, it allows one class to take on some or even all of its attributes and methods from a parent class. The benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) can override or extend the functionality of base classes (ancestors).

52
Q

What is the syntax to indicate that one class inherits from another?

A
When we defined each of our classes, we typed Bike(Vehicle), Car(Vehicle), and Airplane(Vehicle). You could read each of these like "Make a class Bike/Car/Airplane that inherits from Vehicle". This is what is known as the implicit inheritance, which allows us to use inherited attributes and methods of the Vehicle (parent) class in our new subclasses.
eg:
class Parent:

class Child(Parent)

53
Q

What does super mean in the context of OOP?

A

If we want to be able to refer to the parent’s __init__() method, because it still handles setting the other attributes the way we want. This can be true for any method or attribute, we may want to refer to the parent’s version. We would reference that parent object with the keyword super. Specifically, we can reference a parent’s method by calling super().parent_method(). eg:

class Wizard(Human):
def __init__(self):
super().__init__() # use super to call the Human __init__() method
self.intelligence = 10 # every wizard starts off with 10 intelligence, overwriting the 3 from Human
def heal(self):
self.health += 10 # all wizards also get a heal() method

54
Q

Why might a child class need to call a method that belongs to its parent?

A

because it handles setting the other attributes the way we want.

55
Q

How can a child class call a method that belongs to its parent?

A

Specifically, we can reference a parent’s method by calling super().parent_method().

56
Q

What should we do if a function should be able to accept variable amounts of arguments?

A

use the splat operator

57
Q

What does the splat operator do?

A
if you want to pass in a variable number of arguments, or want to capture multiple arguments into a single parameter use the splat operator or the asterisk *
eg:
def varargs(arg1, *args):
    print("Got "+arg1+" and "+ ", ".join(args))
varargs("one") # output: "Got one and "
varargs("one", "two") # output: "Got one and two"
varargs("one", "two", "three") # output: "Got one and two, three"
58
Q

What is test-driven development?

A

s a method of developing software that provides a structure to write good code and ensure an end product that has been tested in each phase of development. The model of TDD is as follows:

Design a feature
Write a test that fails (RED). This test will model a specific behavior or outcome in your code
Write the code that will make your feature work and test pass (GREEN). Also, make sure that tests prior to the feature you are working on are still passing!
Refactor your code and improve your design
Move to the next feature and repeat the process

59
Q

How is the cycle of test-driven development different from the traditional development cycle?

A

As you may have noticed, TDD focuses on testing throughout the entire development process rather than the beginning. Without integrated tests, the software will die as it becomes more complex and ugly because developers don’t touch code for fear of breaking it.

60
Q

What are the pros and cons of test-driven development?

A

The Benefits

TDD will allow us to develop in such a way that:

We have a clear picture of how features should work before building it out
We can develop without the fear of breaking our apps
We can encourage improvement and refactoring of the codebase which will lead to cleaner code
Drawbacks

Larger time investment
Additional complexity of code
More code to maintain

61
Q

When should we use TDD?

A

TDD is generally not worth the cost when working through Dojo assignments – except perhaps for the largest ones such as your final projects for a stack. Once you understand a technology area, feel free to apply TDD, but in general we recommend that you focus on learning how to actually build applications for now.

62
Q

How do we import the Python testing framework?

A
Python's unit testing framework, which was previously known as "PyUnit", is included in the Python standard library.  To import the module type:
import unittest
63
Q

How do we use the Python testing framework to write tests for our code?

A

Create a new file:
test_even.py

# our "unit"
# this is what we are running our test on
def isEven(n):
    if n % 2 == 0:
       return True
    else:
       return False
# our "unit tests"
# initialized by creating a class that inherits from unittest.TestCase
class IsEvenTests(unittest.TestCase):
    # each method in this class is a test to be run
    def testTwo(self):
        self.assertEqual(isEven(2), True)
        # another way to write above is
        self.assertTrue(isEven(2))
    def testThree(self):
        self.assertEqual(isEven(3), False)
        # another way to write above is
        self.assertFalse(isEven(3))
    # any task you want run before any method above is executed, put them in the setUp method
    def setUp(self):
        # add the setUp tasks
        print("running setUp")
    # any task you want run after the tests are executed, put them in the tearDown method
    def tearDown(self):
        # add the tearDown tasks
        print("running tearDown tasks")
if \_\_name\_\_ == '\_\_main\_\_':
    unittest.main() # this runs our tests
64
Q

How do we run the tests we’ve written?

A

if __name__ == ‘__main__’:
unittest.main()

By including these two lines, we can run our test code by executing our python file. Running it with no options results in a simple output but running this file with the -v flag will give you the verbose output with information on each test that was run:

65
Q

What are typical test outcomes in TDD?

A

When we run our tests, there are 3 possible outcomes:

OK - all tests have passed
FAIL - one or more of the tests have failed, and raises an AssertionError exception
ERROR - the test raises an exception other than AssertionError
In the typical TDD workflow:

Think of Feature->Write Tests->Run & Fail->Code->Run & Pass->Refactor->Repeat

66
Q

How do I find the list of functions/assertions available in the unittest framework?

A

Visit the following site:

https://docs.python.org/3.6/library/unittest.html#unittest.TestCase

67
Q

What is a bit?

A

Everything in a computer is 0’s and 1’s. The bit stores just a 0 or 1: it’s the smallest building block of storage.

68
Q

What is a byte?

A

One byte = collection of 8 bits
e.g. 0 1 0 1 1 0 1 0
One byte can store one character, e.g. ‘A’ or ‘x’ or ‘$’

69
Q

How Many Patterns With N Bits?

A

Number of bits Different Patterns
1 0 1
2 00 01 10 11
3 000 001 010 011
100 101 110 111

70
Q

In general, if you add 1 bit what happens?

A
You double the number of patterns.
1 bit - 2 patterns
2 bits - 4
3 bits - 8
4 bits - 16
5 bits - 32
6 bits - 64
7 bits - 128
8 bits - 256 - one byte
Mathematically: n bits yields 2n patterns (2 to the nth power)
71
Q

What is 1 byte?

A

1 byte is group of 8 bits
8 bits can make 256 different patterns
How to use the 256 patterns?
How to store a number in a byte?
Start with 0, go up, one pattern per number, until run out of patterns
0, 1, 2, 3, 4, 5, … 254, 255
One byte can hold a number between 0 and 255
i.e. with 256 different patterns, we can store a number in the range 0..255
Really good for storing characters/letters.

72
Q
What is:
A Kilobyte
A Megabyte
A Gigabyte
A Terabyte
A Petabyte
An Exabyte
A
Kilobyte, KB, about 1024 bytes
Megabyte, MB, about 1024 KB
Gigabyte, GB, about 1024 MB
Terabyte, TB, about 1024 GB
Petabyte, PB, about 1024 TB
Exabyte,  EB, about 1024 PB
Yottabyte, YB, about 1024 EB
73
Q

What is ASCII?

A
Abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. It is an encoding representing each typed character by a number.  Each number is stored in one byte (so the number is in 0..255)
A is 65
B is 66
a is 96
space is 32, etc.
74
Q

What is Unicode?

A

an international encoding standard for use with different languages and scripts, by which each letter, digit, or symbol is assigned a unique numeric value that applies across different platforms and programs.

75
Q

What is a data structure?

A

A data structure is simply a container that holds values. Data structures can organize large quantities of data and make certain operations run much faster.

76
Q

What is a linked list?

A

A data structure that stores values in sequential order. Sounds similar to an array, doesn’t it? Yes, but Linked Lists have other strengths that make them more suited for many problems. Specifically, Linked Lists are optimized for Quick Insertion and Deletion.

The Linked List Object itself only has two attributes, the head and the tail of the Linked List. The head is a pointer to the first node in a List. The tail is a pointer to the last node in this List. This node’s next will always be None, meaning there are no nodes following the last node in this List.

77
Q

What is a node?

A

A node is an object that has a number of attributes that are stored. Only two attributes are mandatory for an Object to be a node: value and next. The value attribute stores exactly that, a value such as a string or a number.

The next attribute is a pointer - a reference to the following node object – the next kid in line.

78
Q

What is a Singly linked list?

A

When a node has only next pointers, then we call a Linked List of these nodes a Singly Linked List, also known as an SList. Each of these node objects are more accurately called SLNode objects.

79
Q

What is a Doubly linked list?

A

If the nodes contain both next and previous pointers, then this is a Doubly Linked List, or DList. Accordingly, each of these node objects would more accurately be called DLNode objects.

80
Q

How do you add a new node to a linked list.

A
Start first by writing the node (SLNode) class:
class SLNode:
 def \_\_init\_\_(self, value):
  self.value = value
  self.next = None
Each new node's next is null until we specify what it should point to.
Next, we will create the SList class.
class SList:
 def \_\_init\_\_(self):
  self.head = None
  self.tail = None
Each new list is empty (contains zero nodes) until we add them to the list.
Now we can run the following code…
list = SList()
list.head = SLNode('Alice')
list.head.next = SLNode('Chad')
list.head.next.next = SLNode('Debra')
81
Q

What is a hash table?

A

is a data structure that implements an associative array abstract data type, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

82
Q

What is a binary search tree?

A

sometimes called ordered or sorted binary trees, are a particular type of container: data structures that store “items” (such as numbers, names etc.) in memory. They allow fast lookup, addition and removal of items, and can be used to implement either dynamic sets of items, or lookup tables that allow finding an item by its key (e.g., finding the phone number of a person by name).

83
Q

What is a stack?

A

A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.
A stack is a recursive data structure. Here is a structural definition of a Stack:

a stack is either empty or
it consists of a top and the rest which is a stack;

84
Q

Define polymorphism

A

Polymorphic behavior allows us to specify common methods in an “abstract” level and implement them in particular instances. It is the process of using an operator or function in different ways for different data input.

# We'll use the Person class to demonstrate polymorphism
# in which multiple classes inherit from the same class but behave in different ways
class Person:
  def pay_bill(self):
      raise NotImplementedError
# Millionaire inherits from Person
class Millionaire(Person):
  def pay_bill(self):
      print("Here you go! Keep the change!")
# Grad Student also inherits from the Person class
class GradStudent(Person):
  def pay_bill(self):
      print("Can I owe you ten bucks or do the dishes?")
85
Q

What are ORMs?

A

ORMs are used to create a language-specific object oriented representation of a table. When tables are objects, attributes of these objects represent the columns in the database, while methods will correspond to common queries.

The reason that ORMs are useful is so that we can write pure Python code without having to manage long SQL query strings in our logic.

86
Q

What is the ForeignKey statement?

A

statement is the equivalent of the one-to-many relationship shown in the ERD diagram.

87
Q

What are routes?

A

A route is much like a variable name we assign to a request. The job of a route is to communicate to the server what kind of information the client needs. This route name is attached to a route on our server that points towards a specific set of instructions. These instructions contain information about how to interpret the data being sent, the operations that need to be completed, and the response that should be sent back. These instructions are the code we’ll be creating!

Every route has two parts:

HTTP method (GET, POST, PUT, PATCH, DELETE)
URL
88
Q

What is the HTTP request/response cylce?

A

Your browser makes a request to a URL and receives a response from the web server, displaying the HTML, CSS and JavaScript in your browser.
Imagine doing your holiday shopping online. While filling your shopping cart with the gifts you’ve selected you will do the following:

Visit the home page of your retailer of choice
Log into your account
Submit search queries
Browse the items from the resulting list
View select items in detail
Add certain items to your shopping cart
Check out
Receive confirmation of your order
Each one of those steps along the way is a full HTTP request/response cycle. It begins with your browser sending a request, and ends with the browser rendering a response from the server.
89
Q

In the HTTP request/response cycle what does it mean to be stateless?

A

That means that each request/response cycle instance is independent and ignorant of any instances that came before or will come after it. This matters because, along with each request, your favorite retailer always knows and remembers:

Who you are (your account)
What you’ve searched for
The items in your cart
etc…

90
Q

What is session?

A

Persistent data storage that allows users to read pieces of data that was stored in previous cycles and write certain valuable pieces of data for use in future cycles. In other words, the user can make decisions that can be tracked so that the server can respond appropriately to create a better user experience.

91
Q

What is a cookie?

A

used to store data like sessions. sends a packet of information from the server to the client. This packet is known as a cookie. Once your browser has received this cookie, it writes the information contained in it to a small file on your hard drive. Django stores session data in the database, sending only secure keys that can be used to retrieve data from a database only when required.

92
Q

What are hidden input fields?

A

form fields that are hidden from the user. Hidden input is used, along with other input elements, to transfer information between different pages.

A hidden input is just an ordinary input element but has a type of “hidden”, which means there will be no visual representation in the rendered HTML, but the form element IS usable by the method where the form is sent. But know that, even though hidden inputs are invisible to the user, it is actually very visible in the page’s source. That means other users can still see and change the values you set in the hidden input. So be very careful in choosing what data you store in there as value, and set appropriate actions if a user tries to change or remove it.

93
Q

What is a database?

A

Databases are merely collections of organized information that can easily be accessed, managed, and updated.

94
Q

What is ERD?

A

ERD is short for ‘Entity Relationship Diagram’. That’s just a fancy way of saying that ERDs are essentially visual blueprints for how your database looks and behaves. ERDs and SQL work together very intimately. An ERD is a map of the structure of how we want to store our data, and SQL is the language we use to manipulate the data as per the relationships we defined in our ERD. Learning database design first will help us visualize how our relational databases look, making it much easier to pick up the actual SQL syntax.

ERD is a process of laying out your tables and establishing relationships between them, making your data relational. Just about any data imaginable can be stored in a relational manner, there really isn’t anything you can’t do using a relational database like MySQL.

95
Q

What does the acronym DRY mean?

A

Do Not Repeat Your code or your data

96
Q

What are the types of database relationships?

A

One to One
One to Many
Many to Many

97
Q

What does it mean to normalize your data?

A

It means we normalize our tables to insure the data is not repeated and ultimately use our storage space more efficiently. Also we make our database more modular so that we can create more variety of customized tables.

98
Q

What are the 3 forms of database normalization?

A

First Form
Each Column in your table can only have 1 value.
Ex. You should not have an address column in your table that lists the address, city, state, and zip, all separated by commas.

Second Form
Each Column in your table that is not a key (primary or foreign) must have unique values.
Ex. If you have a movies table with a categories column, you should not have a category repeated more than once.

Third Form
You cannot have a non-key column that is dependent on another non-key column.

99
Q
A real world parallel of a primary key would be which one of the following:
 Social Security Number
 Birthday
 Street Address
 Last Name
A

Social Security Number

100
Q

Which of the following relationships requires a foreign key?

Many to Many
One to One
One to Many
All of the Above

A

All of the Above

101
Q

Which of the following is the best example of a many to many relationship

users have many photos and photos have many users
users have many interests and interests have many users
blogs have many posts and posts have many blogs
messages have many comments and comments have many messages

A

users have many interests and interests have many users

102
Q

Which of the following violates the first form of normalization

Having a column in your products table called assembly which contains the information for how to assemble the product.
Removing the type column from your products table and adding a relationship of ‘products has-many types’
Having a column in your products table with a comma-separated list of all the different categories that the product belongs to
Separating out price from the products table to create a prices table with a relationship of ‘products has-one price’

A

Having a column in your products table with a comma-separated list of all the different categories that the product belongs to

103
Q

In a One to One relationship the joining tables are related by having a foreign key in both tables

True
False

A

False

104
Q

In the relationship of ‘states has-many cities’, the foreign key that joins the tables together goes in the states table.

A

False

105
Q

To pass the second form of normalization, you should find any non-key columns that have repeated values and separate them out into another table and create the proper relationship.

A

True

106
Q

A users table with profile_pic_name and profile_pic_url columns
A pictures table with url and name columns
A many to many relationship without a joining table
Having an interests column in your students table that lists out each students different interests

A

A users table with profile_pic_name and profile_pic_url columns

107
Q

What is the most important thing to remember about database design?

A

Making sure we don’t repeat data

108
Q

What is the main purpose for Normalization?

A

Creating a convention for organizing and avoiding the duplication of data

109
Q

Define information hiding.

A

Allows us to use other people’s code without having a deep understanding of how it was written

110
Q

Define modularity.

A

Breaks down complex logic into smaller components or modules and makes it easier for someone else to read, understand, use and build upon our code.

111
Q

Define abstraction.

A

When programmers generalize code so that they can reuse the same functions in multiple situations across a project to maximize its usefulness. It reduces a code’s complexity, especially for larger projects.

112
Q

what are built-in functons.

A

functions that python has defined for us.

113
Q

what are optional arguments?

A

they have default values that they take on unless a different value is provided by the user.

114
Q

When do runtime errors occur?

A

When the code is actually running, which makes them harder to catch and prevent beforehand. Examples are:
~calling a function before it’s defined
~calling a method or attribute that the object doesn’t contain
~attempting to convert a value to an incompatible data type

115
Q

What does python’s interpreter use to represent errors?

A

The SyntaxError class and displays the error message after the colon. The interpreter may sometimes struggle to pinpoint the problematic code that caused the error.

116
Q

What is dot notation?

A

When we import a module, we can access its functions and variables using a period.
eg
my_module.some_function

117
Q

Define namespace

A

a dictionary that contains all of the names we can refer to in our code. The python interpreter adds all of the objects and functions that are available by default ie print(), list(), etc to the global namespace.

118
Q

how do you open a csv file?

A

open_csv = open(‘dataset/myfile.csv’, ‘r’)

it returns a delimited string

119
Q

why use the csv module?

A

we can work with csv files more easily. it has a reader() function that takes a file object as its argument and returns an object that represents the data. ie.
import csv
open_csv = open(‘dataset/myfile.csv’, ‘r’)
csvreader = csv.reader(open_csv) #creates an object
my_data = list(csvreader) #convert to a list

120
Q

What is python’s self variable that is used when defining a class?

A

It is used to refer to the created object so you can interact with the instance. If you didn’t have self, then the class wouldn’t know where to store the internal data you wanted to keep. By convention self is used to define the instance even though it’s possible to use any name.

121
Q

What’s a great function to help search and extract both the index and label of a list?

A

enumerate()