Binary Math

All questions answered (0.9)

Fill in the blank spots below during the lecture

Opearator Name Action
& AND Only true if both are true
OR True if at least one is true
^ XOR Only returns true if both are true or both are false
~ NOT Inverts true to false and false to true
<< Left Shift Shifts left, essentially
>> Right Shift Shifts right, essentially
>>> Zero-fill Right Shift Goes immediately to the right, essentially. The same applies for the left shift zero-fill

Bitwise operations are used in a variety of applications, particularly in low-level programming and computer science. Some common used of bitwise operations include:> - Flag Management: Flags are used to keep track of the state of a system or a program. Bitwise operations can be used to set, clear, and toggle flags.> - Bit Manipulation:Bitwise operations can be used to individual bits in a binary number. This is often used to extract specific bits from a number, set specific bits to a particular value, or flip the value of specific bits.> - Masking:Masking is used to extract a specific subset of bits from a binary number. Bitwise operations are commonly used for masking, particularly in low-level programming.> - Encryption:Bitwise operations can be used in cryptographic applications to scramble and unscramble data. One common application of bitwise operations in encryption is the XOR operation.> - Graphics:Bitwise operations can be used in computer graphics to manipulate individual pixels on a screen. This can be used to draw shapes, change colors, and create special effects.> - Networking:Bitwise operations are used extensively in networking applications, particularly in the handling of IP addresses and port numbers.

What are some situations in which binary search could be used?

  • Searching a dictionary
  • Searching a list
  • Guessing a number
  • Guessing an element in a list with an index

No quiz (0.9)

Binary Code:

def decimal_to_binary(decimal):
    """Converts decimal to binary."""
    binary = bin(decimal)[2:]
    return binary

def binary_to_decimal(binary):
    """Converts binary to decimal."""
    decimal = int(binary, 2)
    return decimal

def perform_operation(num1, num2, operation):
    """Performs the given operation on binary numbers and returns the result in decimal."""
    binary_num1 = decimal_to_binary(num1)
    binary_num2 = decimal_to_binary(num2)

    if operation == '+':
        result = binary_to_decimal(binary_num1) + binary_to_decimal(binary_num2)
    elif operation == '-':
        result = binary_to_decimal(binary_num1) - binary_to_decimal(binary_num2)
    elif operation == '*':
        result = binary_to_decimal(binary_num1) * binary_to_decimal(binary_num2)
    elif operation == '/':
        result = binary_to_decimal(binary_num1) / binary_to_decimal(binary_num2)
    else:
        print("Invalid operation. Please try again.")
        return

    return result

num1 = int(input("Enter the first number: "))
print(num1)
operation = input("Enter the operation (+, -, *, /): ")
print(operation)
num2 = int(input("Enter the second number: "))
print(num2)

result = perform_operation(num1, num2, operation)

if result is not None:
    print("Result in decimal: ", result)
5
+
6
Result in decimal:  11

SASS and JavaScript

JavaScript

A takeaway from this lesson that I didn't know before:Identifying keys and values. Here is how I answered the question here (0.9): Object

  • Identify the name/keys in the object below: name, breed, age, color
  • Identify the values in the object below: Elly, Rottweiler, 4, black Questions (0.9)
  1. Where do you store the JavaScript Code?

Either in a ".js" file or using the script tag

  1. How do you import a JS file into HTML?

You can use the syntax:<script src="script.js"></script> at the end of the html body.

  1. What is onClick?

Onclick is an attribute in the <button> element that allows for a JavaScript function to be called when the button is clicked or pressed by the user.

  1. What tag do you use to write JavaScript code?

As mentioned, you can use the <script> tag to write JavaScript code in an HTML document or write JavaScript in another ".js" file and reference it in your HTML document using the src="" attribute.

Coding a JavaScript Game (0.9). For this hack, I remade Pong using JavaScript and the <canvas> tag in HTML.

// If needed, I can explain all of the code detailed in a live review.

const canvas = document.getElementById('pong');
const ctx = canvas.getContext('2d');

const ball = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  radius: 10,
  speedX: 2,
  speedY: 2,
  draw: function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = '#fff';
    ctx.fill();
    ctx.closePath();
  }
};

const paddleWidth = 15;
const paddleHeight = 60;

const paddleA = {
  x: 0,
  y: canvas.height / 2 - paddleHeight / 2,
  width: paddleWidth,
  height: paddleHeight,
  speedY: 2,
  draw: function() {
    ctx.fillStyle = '#fff';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};

const paddleB = {
  x: canvas.width - paddleWidth,
  y: canvas.height / 2 - paddleHeight / 2,
  width: paddleWidth,
  height: paddleHeight,
  speedY: 2,
  draw: function() {
    ctx.fillStyle = '#fff';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};

function update() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  ball.x += ball.speedX;
  ball.y += ball.speedY;
  
  if (ball.y < ball.radius || ball.y > canvas.height - ball.radius) {
    ball.speedY *= -1;
  }
  
  if (ball.x < 0) {
    ball.x = canvas.width / 2;
    ball.y = canvas.height / 2;
    ball.speedX = 2;
    ball.speedY = 2;
  } else if (ball.x > canvas.width) {
    ball.x = canvas.width / 2;
    ball.y = canvas.height / 2;
    ball.speedX = -2;
    ball.speedY = -2;
  }
  
  ball.draw();
  paddleA.draw();
  paddleB.draw();
  
  requestAnimationFrame(update);
}

update();

SASS

Questions Answered (0.45):1. What is nesting in SASS? Nesting refers to the practice of nesting CSS rules within other CSS rules, which allows for more organized and hierarchical styling of HTML elements. Nesting is one of the features of SASS that makes it a powerful and efficient CSS preprocessor. SASS allows you to write CSS rules in a nested structure, where child selectors are written inside their parent selectors. This creates a visual hierarchy that is easier to read and understand, and also helps to avoid repetitive code.

  1. What are similarities and differences you notice about the buttons?

The buttons are all the same width and height, but they are different colors and one of them is a radial gradient.

  1. What is extending and inheritance in SASS?

Extending or inheritance is a feature that allows you to define a CSS rule or selector with common styles, and then extend or inherit those styles in other CSS rules or selectors. This helps in creating reusable styles and reduces code duplication. In SASS, you can use the @extend directive to extend a CSS rule or selector from one place to another.

  1. What is a Mixin in SASS?

A mixin is a reusable block of code that can be defined once and then included or "mixed in" to multiple CSS rules or selectors. Mixins in SASS are similar to functions or procedures in programming languages, allowing you to define a block of styles and then reuse it in multiple places in your CSS code. Mixins in SASS are defined using the @mixin directive, and they can accept parameters, allowing you to create dynamic styles.

  1. What is a function in SASS?

A function is a reusable piece of code that can be defined once and then called with arguments to perform calculations or generate values dynamically. Functions in SASS are similar to functions in programming languages and can be used to create dynamic styles or perform calculations on values. SASS provides a set of built-in functions, such as rgb(), rgba(), darken(), lighten(), mix(), round(), percentage(), etc., which can be used to perform various operations on color values, numeric values, strings, and other data types. In addition to the built-in functions, SASS allows you to define your own custom functions using the @function directive.

  1. What is importing in SASS?

The @import directive is used to include the contents of one SASS file into another. It is a way to modularize your CSS code and split it into separate files for better organization, reusability, and maintainability. The @import directive allows you to include the styles from one SASS file into another, similar to how you might use import in other programming languages. When the SASS compiler processes a file with an @import directive, it imports the contents of the specified file and combines them into a single CSS output.

Mini-Hacks Completed (0.45):1. CSS:``` .a .b { color: green; }

.a .c { color: blue; }

SASS:

.a { .b { color: green; }

.c { color: blue; } } ```

  1. Write out a mixin in SASS that takes in a color and a font size as the parameter. Within the mixin, set the background color and font color to the color parameter, and set the font size to the font size parameter. Then create a selector that calls the mixin, and pass in a color and font size of your choice as the arguments.

My choice of font size and color respectively are 25px and black.

@mixin customStyles($color, $font-size) {
  background-color: $color;
  color: $color;
  font-size: $font-size;
}

.my-element {
  @include customStyles(black, 25px); // Call the mixin and pass in values for parameters
}

Multiple-choice answers (0.9):1. B2. A

  1. A
  2. B
  3. D
  4. B
  5. B

Using SASS to demonstrate @extend and @mixin (0.9):```@mixin customButton { background-color: blue; color: white; padding: 10px; font-size: 16px; text-align: center; }

.button { @include customButton; }

.submit-button { @extend .button; background-color: green; }

.cancel-button { @extend .button; background-color: red; } ```

Extra Credit:Researching more features of SASS: ``` / Define a variable / $primary-color: #ff5500;

/ Use SASS color functions / .container { background-color: darken($primary-color, 10%); color: complement($primary-color); border: 1px solid lighten($primary-color, 20%); }

/ Use SASS control directives / @for $i from 1 through 5 { .element-#{$i} { font-size: $i * 10px; } }

/ Use SASS parent selector / .parent { .child { &:hover { color: red; } &::after { content: " (Child)"; } } }

/ Use SASS placeholder selector / %my-placeholder { font-style: italic; }

.my-element { @extend %my-placeholder; font-weight: bold; } ``` In the above example, we make use of features of SASS you probably didn't know:

  1. SASS color functions: We use color functions like darken(), complement(), and lighten() to dynamically manipulate colors based on the $primary-color variable.

  2. SASS control directives: We use the @for directive to loop through a range of numbers and generate CSS classes with different font sizes.

  3. SASS parent selector: We use the & selector to reference the parent selector within nested selectors, allowing us to generate more specific CSS rules based on the parent selector.

  4. SASS placeholder selector: We define a placeholder selector %my-placeholder which is not output in the final CSS, but can be extended using the @extend directive to share styles among multiple selectors without generating redundant CSS code.

Data Analysis with Pandas and Numpy

Blanks Filled (0.15):Predictive analysis is the use of statistical, data mining, and machine learning techniques to analyze current and historical data in order to make predictions about future events or behaviors. It involves identifying patterns and trends in data, and then using that information to forecast what is likely to happen in the future. Predictive analysis is used in a wide range of applications, from forecasting sales and demand, to predicting customer behavior, to detecting fraudulent transactions. It involves collecting and analyzing data from a variety of sources, including historical data, customer data, financial data, and social media data, among others.

The process of predictive analysis typically involves the following steps:

  1. Defining the problem and identifying the relevant data sources
  2. Collecting and cleaning data
  3. Exploring and analyzing the data to identify patterns and trends
  4. Selecting an appropriate model or algorithm to use for predictions
  5. Training and validating the model using historical data
  6. Using the model to make new predictions
  7. Monitoring and evaluating the performance of the model over time

Predictive analysis can help organizations make more informed decisions, improve efficiency, and gain a competitive advantage by leveraging insights from data.

It is most commonly used in retail, where workers try to predict which products would be most popular and try to advertise those products as much as possible, and also healthcare, where algorithms analyze patterns and reveal prerequisites for diseases and suggest preventive treatment, predict the results of various treatments and choose the best option for each patient individually, and predict disease outbreaks and epidemics.

An array is the central data structure of the NumPy library. They are used as containers which are able to store more than one item at the same time. Using the function np.array is used to create an array, in which you can create multidimensional arrays.

One of the most basic operations that can be performed on arrays is arithmetic operations. With numpy, it is very easy to perform arithmetic operations on arrays. You can add, subtract, multiply, and divide arrays, just like you would with regular numbers. When performing these operations, numpy applies the operation element-wise, meaning that it performs the operation on each element in the array separately. This makes it easy to perform operations on large amounts of data quickly and efficiently.

Numpy provides a convenient and powerful way to perform data analysis tasks on large datasets. One of the most common tasks in data analysis is finding the mean, median, and standard deviation of a dataset. Numpy provides functions to perform these operations quickly and easily. The mean function calculates the average value of the data, while the median function calculates the middle value in the data. The standard deviation function calculates how spread out the data is from the mean. Additionally, numpy provides functions to find the minimum and maximum values in the data. These functions are very useful for gaining insight into the properties of large datasets and can be used for a wide range of data analysis tasks.

Popcorn Hacks Completed (0.15):1. How could you create a 3D array based on knowing how to make a 1D array?

array_3d = [[[0 for _ in range(2)] for _ in range(4)] for _ in range(3)]

array_3d[0][0][0] = 1
array_3d[1][2][1] = 2
array_3d[2][3][0] = 3

print(array_3d[0][0][0])
print(array_3d[1][2][1])
print(array_3d[2][3][0])
1
2
3
  1. Now from learning this, can you find a different way from how we can solve the sum or products of a dataset other than how we learned before? Create a different way of solving the sum or products of a dataset from what we learned.
import numpy as np

data = np.array([1, 2, 3, 4, 5])

sum_data = np.sum(data)
sum_data_manual = np.sum(data[:])

product_data = np.prod(data)
product_data_manual = np.prod(data[:])

print("Dataset:", data)
print("Sum using sum():", sum_data)
print("Sum using array indexing:", sum_data_manual)
print("Product using prod():", product_data)
print("Product using array indexing and multiplication:", product_data_manual)
Dataset: [1 2 3 4 5]
Sum using sum(): 15
Sum using array indexing: 15
Product using prod(): 120
Product using array indexing and multiplication: 120

Dataset with Panda and NumPy:

import pandas as pd
import numpy as np

# Pandas Hacks #

df = pd.read_csv('files/padres.csv').sort_values(by=['Name'], ascending=False)

print("--Duration Top 10---------")
print(df.head(10))

print("--Duration Bottom 10------")
print(df.tail(10))
print(', '.join(df.tail(10)))

# What's happening in the code? 

# Since this is code from the lesson, to actually complete the hacks, I will explain what is happening in
# the code. First, we import the Pandas library. Then, we use Pandas to read the CSV file and collect the
# data, sorting it by name. Then, we use the Pandas head() method with a parameter of 10 to get the top
# 10 datasets. To do the inverse, we use the tail() method with the same parameter to get the 10 at the
# bottom. Finally, we use the string's join() method to format the dataset so that it is more readable.
# A misconception someone might have is that the join() method is part of Pandas. However, it is actually
# part of Python's built in string methods. Overall, I got the maximum and mininum values, sorted the
# dataset, and had the datasets merged.


# NumPy Hacks #


# Random number generator:
random_number = np.random.rand()
print("Random number:", random_number)

# 5-dimensional array:
array_5d = np.zeros((2, 3, 4, 5, 6))
print("Shape of 5D array:", array_5d.shape)

# Array with linearly spaced intervals between values
start = 1
stop = 5
num = 10
lin_space_array = np.linspace(start, stop, num)
print("Linearly spaced array:", lin_space_array)

Simulations and SQLite Notes

Blanks filled (0.3):What is the output of the cell below? What Mathematical Expressions do you see being used? (List them below.)

  • The output is the average of the two grades
  • I see both addition and floor division being used.

What is the value of num1, num2, and num3? Explain how each number ended up what it was.

  • Num1 Was originally 2, but it is now 4 raised to the 6th power, which is 4096.
  • Num3 was originally 6, but it is now the remainder of 4096 divided by 5.
  • Num2 was originally 4, but it is now the rounded division of the sum of 4096 and 455 divided by 9.

Selection refers to the process of making decisions in a program based on certain conditions. It is normally done with conditional statements.

What is a conditional?:

  • Statement that allows code to execute different instructions if a certain condition is true or false
  • Allows program to make decisions based on data and input

What are the main types of conditional statements?:

  • if
  • elif
  • else

  • The if statement is used to check if a certain condition is true. The condition can be any expression that evaulates to a boolean value, True or False. If the condition is True, then it executes a code block.

  • If (condition) then (consequence)
  • Example:

  • The else statemnt executes a code block when the if condition is False.

  • If (condition) then (consequence A), else (consequence B)

  • The elif statement can check multiple conditions in a sequence, and execute a certain block of code if any of the conditions are true.

  • If (condition) then (consequence A), elif (condition) then (consequence B), else (consequence C)

  • Example adding onto the code from before to take negative numbers and 0 into account

What is a nested conditional?:

  • Conditional statement inside another conditional statement
  • Allows to check for more complex condition where one condition depends on another

When using conditionals and nested conditionals in Python, it is important to pay attention to the level of indentation in the code. The code inside the if, elif, and else blocks must be indented so they are nested wihtin the outer statements. This way, Python knows which code belongs to which block.

What is binary search and what is it used for?:

  • It is a searching algorithm
  • Find and select a specific element in a sorted list of elements

How does binary search work?:

  • Repeatedly divides the search interval in half to find the middle element and compares the middle value to the target value, if not the same then it continues on to either the lower or upper half
  • Eliminate half of the remaining search interval elements each time
  • Efficient way to search for element in large dataset

What is the time complexity and why?:

  • O(log(N))
  • The maximum number of iterations is the amount of times the list can be divided in half until it reaches 1 number
  • Dividing by 2, so it is log2(N), logarigthm of n base 2

  • You may recognize the example below from the binary lesson last Friday

  • an algorithm is a set of instructions that describes how to solve a problem or perform a specific task using a computer program.

  • It is a precise sequence of computational steps that take an input and produce an output

  • Algorithms often rely on specific data structures to solve problems efficiently.

  • Sorting algorithms require a data structure such as an array or a linked list to store and manipulate data.
  • Searching algorithms such as binary search require data structures like arrays or trees to organize and search through data.

  • it is a finite set of instructions set of instructions that accomplishes a specific task

  • means that there is an order in which to do things

  • Helps to choose two different outcomes based off of a decision that the programmer wants to make

  • Repeat something until the condition is met. (also referred to as repetition)

  • A procedure is a sequence of instructions that performs a specific task.

  • To call a procedure, you need to know its name and any arguments it requires.
  • When a procedure is called, the program jumps to its instruction and starts executing it.
  • The arguments passed to a procedure can be used within the procedure to perform tasks or calculations.
  • After the procedure has completed its task, it returns control back to the calling program.

  • The result of the procedure can be stored in a variable, printed to the screen, or used in any other way that is required by the program.

  • Procedures can be defined within the same program or in external files, and can be reused across multiple parts of the program.
  • To avoid errors and improve code readability, it's important to define and call procedures with proper syntax and conventions that are appropriate for the programming language you're using.

  • Algorithmic efficiency refers to the amount of time and resources needed to execute an algorithm.

  • The efficiency of an algorithm can be measured in terms of its time and space complexity.

    • Time complexity refers to the amount of time required by an algorithm to complete its task as a function of its input size.
    • Space complexity refers to the amount of memory required by an algorithm to complete its task as a function of its input size.
    • can be analyzed using Big O Notation, which provides an upper bound on the worst-case time and space complexity of the algorithm.
  • What is the time complexity of the following code:

    • O(N)
    • O(N*log(N))
    • O(N * Sqrt(N))
    • O(N*N)
  • What will be the time complexity of the following code?

  • n

  • (n+1)
  • n(n-1)
  • n(n+1)

  • Efficiency can be improved by optimizing algorithms or by using more efficient data structures and algorithms.

    • Some common techniques for improving efficiency include reducing the size of input data, caching results, and parallelizing tasks.
    • Understanding algorithmic efficiency is important in software development, as it can impact the performance of applications and their ability to scale with larger data sets.

Simulations are models of real-world phenomena or systems that use mathematical algorithms and computer programs simulate the real behavior and aspects of the subject being modeled.

Simulations are most often used to model complex or time-consuming that would be difficult to test in real life, such as modeling the spread of diseases in certain ecosystems or testing the functionality of a potential product before it is made.

In this lesson, we will be looking at lists, iteration, and random values through the lens of simulations.

For loops are probably the most well-known type of iterative loop used in code. Most of us know about the for variable in list format.

One helpful tool not a lot of people know about is the enumerate() function. When used in conjunction with a for loop, you can always have access to the index and value of each selected list entry.

While loops aren't used in the program, but they offer a different way to repeat a set of instructions in a program. The procedure below the while [condition] line will occur until the condition is made not true.

Student Interaction: How could this build function be altered to function with a while loop within it?

import random

rand_card = deck[random.randint(0, 2)]
print(rand_card)
<__main__.Card object at 0x7f83a2ee1880>
import random

# population variables
START_POP = 500
MAX_POP = 1000
MIN_POP = 0
MAX_CHANGE = 50
MIN_CHANGE = -50

# year variables
START_YEAR = 0
END_YEAR = 10

# initialize population list
population = [START_POP]

# simulate population changes over time
for year in range(START_YEAR + 1, END_YEAR + 1):
    # get a random population change value
    change = random.randint(MIN_CHANGE, MAX_CHANGE)
    
    # add change to previous year's population
    new_pop = population[year-1] + change
    
    # check that population is within limits
    if new_pop > MAX_POP:
        new_pop = MAX_POP
    elif new_pop < MIN_POP:
        new_pop = MIN_POP
    
    # add new population value to list
    population.append(new_pop)
    
# print final population list
for year, pop in enumerate(population):
    print(f"Year {year}: {pop}")

# In this simulation, we simulate the changes in wildlife population over a 10-year period. 
# We start with a list of the population of the area for each year, and use a for loop to 
# iterate over the 10 years. In each iteration, we randomly select a factor that affects 
# population growth (such as drought, flood, fire, disease, or predation), and use a series 
# of conditionals to calculate the change in population based on the factor and the previous 
# year's population. We then update the population list with the new value, and print the 
# result for the year. This simulation includes the use of a random value, a list, iteration,
# and conditionals.
Year 0: 500
Year 1: 473
Year 2: 443
Year 3: 482
Year 4: 458
Year 5: 500
Year 6: 480
Year 7: 484
Year 8: 496
Year 9: 498
Year 10: 457
from flask import Flask
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'databasehw.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
api = Api(app)
db = SQLAlchemy(app)


class MyDataModel(db.Model):
    __tablename__ = 'my_data_model'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    age = db.Column(db.Integer)
    email = db.Column(db.String(120))

    def __init__(self, name, age, email):
        self.name = name
        self.age = age
        self.email = email

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'age': self.age,
            'email': self.email
        }


class MyDataResource(Resource):
    def get(self, id=None):
        if id:
            my_data = MyDataModel.query.filter_by(id=id).first()
            if not my_data:
                return {'message': 'Data not found'}, 404
            return my_data.to_dict()
        else:
            my_data = MyDataModel.query.all()
            return [data.to_dict() for data in my_data]

    def post(self):
        data = request.get_json()
        my_data = MyDataModel(data['name'], data['age'], data['email'])
        db.session.add(my_data)
        db.session.commit()
        return my_data.to_dict(), 201

    def put(self, id):
        data = request.get_json()
        my_data = MyDataModel.query.filter_by(id=id).first()
        if not my_data:
            return {'message': 'Data not found'}, 404
        my_data.name = data['name']
        my_data.age = data['age']
        my_data.email = data['email']
        db.session.commit()
        return my_data.to_dict()

    def delete(self, id):
        my_data = MyDataModel.query.filter_by(id=id).first()
        if not my_data:
            return {'message': 'Data not found'}, 404
        db.session.delete(my_data)
        db.session.commit()
        return {'message': 'Data deleted successfully'}


api.add_resource(MyDataResource, '/my-data', '/my-data/<int:id>')


if __name__ == '__main__':
    app.run()
    
# This program creates a simple Flask application with a single resource called MyDataResource that 
# allows you to perform CRUD operations on a database table called my_data_model. To run this 
# program, save it as a Python file (e.g. app.py) and run it using the command python app.py in your 
# terminal. This will start the Flask development server, and you can test the API using a tool 
# like Postman or cURL.
 * Serving Flask app '__main__'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit

User Database

Blanks Filled (0.3):In Python, classes are templates used to create objects, which are instances of those classes. Classes define the data elements (attributes) and methods that describe the behavior of the objects. Let's explore how to define a class and create objects in Python. In the context of backend functionality, this class can be used to create, manage, and manipulate user data. For example, when a new user signs up for an account, you could create a new User object with their username and email. This object can then be used to perform various operations, such as validating the user's input, storing the user's data in a database, or processing user-related requests.

In Python, classes are templates used to create objects, which are instances of those classes. Classes define the data elements (attributes) and methods that describe the behavior of the objects. Let's explore how to define a class and create objects in Python.

Property decorators allow developers to access and modify instance data more concisely. The @property decorator creates a getter method, while the @attribute.setter decorator creates a setter method.

In the context of backend functionality, this Employee class can be used to model employees within an application. You can create instances of this class to store and manage employee data, and the getter and setter methods can be used to access and modify employee information in a controlled way.

In the context of backend functionality, this Car class can be used to model cars within an application. You can create instances of this class to store and manage car data, and the getter and setter methods can be used to access and modify car information in a controlled way.

SQLite is a software library that provides a relational database management system. Unlike other databases, such as MySQL or PostgreSQL, SQLite is embedded within an application, which means it does not require a separate server process to operate. This makes SQLite a great choice for small-scale applications or for use in situations where you don't want to set up a full database server.

In this lesson, we will be demonstrating how to set up a SQLite database in Flask, which provides an easy-to-use interface for interacting with SQLite databases, and we'll walk through the process of setting up a new database, creating tables, and adding data. We'll also cover some basic SQL commands that you can use to interact with your database, including CREATE TABLE, INSERT, SELECT, UPDATE, and DELETE. By the end of this lesson, you'll have a good understanding of how to work with SQLite databases in Flask and be ready to start building your own applications.

One of the key features of Flask is its ability to work seamlessly with databases, including SQLite. A database is a collection of data stored in an organized manner that can be easily accessed, managed, and updated.

SQL is really useful because it helps people do a bunch of things with the data stored in databases. For example, they can use it to create new tables to organize data, add new data to a table, update data that's already there, or delete data that's no longer needed.

This block of code is a menu function that helps with create, read, update, and delete (CRUD) tasks and displays the schema. The menu function acts as a control point that directs the program to call different functions based on what the user wants to do. When users enter their preferred action, the input is checked to see which function to use. The menu function is created with no arguments and is called repeatedly, displaying the menu options until the user decides to leave.

The create() function allows users to input information about a coding professor and store it in a SQLite database named 'professors.db'. This script prompts the user for the professor's name, field of expertise, rating out of 10, and any reviews or comments about the professor. It then establishes a connection to the SQLite database and creates a cursor object for executing SQL commands.

This code demonstrates how to read data from a SQLite database using Python and the SQLite3 library. The first step is to establish a connection to the database and create a cursor object to execute SQL commands. Then, a SELECT query is executed to fetch all records from the "professors" table. If there are any records, the code iterates through each record and prints out the name, field of expertise, rating, and reviews for each coding professor. If there are no records in the table, a message indicating so is printed.

This is an implementation of an update function for the professors database using the sqlite3 module in Python. The function first establishes a connection to the database file 'instance/professors.db' and creates a cursor object to execute SQL commands. It prompts the user to enter the name of the professor to update and retrieves the corresponding record from the database using a SELECT statement with a WHERE clause to match the professor's name. If the professor is found in the database, the user is prompted to enter new information for the professor's field of expertise, rating, and reviews. The function then executes an UPDATE statement with the new information to update the record in the database.

This code is a Python function for deleting a record from a SQLite database. The function prompts the user to input the name of the professor they want to delete. It then uses a SQL query to search for the professor in the database. If the professor is found, the user is prompted to confirm the deletion. If the user confirms, the function executes a SQL command to delete the record from the database. The function also prints a message confirming that the professor has been deleted from the list of coding professors. If the professor is not found in the database, the function prints a message indicating that the professor is not in the list.

Interactive Coding Lessons + Database Coding, all in one:

import sqlite3

class Database:
    def __init__(self, db_name):
        self.conn = sqlite3.connect(db_name)
        self.cur = self.conn.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, uid TEXT, password TEXT)")
        self.conn.commit()

    def create_user(self, name, uid, password):
        self.cur.execute("INSERT INTO users (name, uid, password) VALUES (?, ?, ?)", (name, uid, password))
        self.conn.commit()

    def read_user(self, uid):
        self.cur.execute("SELECT * FROM users WHERE uid=?", (uid,))
        return self.cur.fetchone()

    def update_user(self, uid, name=None, password=None):
        if name:
            self.cur.execute("UPDATE users SET name=? WHERE uid=?", (name, uid))
        if password:
            self.cur.execute("UPDATE users SET password=? WHERE uid=?", (password, uid))
        self.conn.commit()

    def delete_user(self, uid):
        self.cur.execute("DELETE FROM users WHERE uid=?", (uid,))
        self.conn.commit()

if __name__ == '__main__':
    db = Database("databasehw.db")

    method = input("Which method would you like to use? (create, read, update, delete) ")

    if method == "create":
        name = input("Enter user name: ")
        uid = input("Enter user ID: ")
        password = input("Enter user password: ")
        db.create_user(name, uid, password)
        print("User created.")

    elif method == "read":
        uid = input("Enter user ID: ")
        user = db.read_user(uid)
        if user:
            print(f"Name: {user[1]}, ID: {user[2]}, Password: {user[3]}")
        else:
            print("User not found.")

    elif method == "update":
        uid = input("Enter user ID: ")
        name = input("Enter new user name (leave blank to skip): ")
        password = input("Enter new user password (leave blank to skip): ")
        db.update_user(uid, name, password)
        print("User updated.")

    elif method == "delete":
        uid = input("Enter user ID: ")
        db.delete_user(uid)
        print("User deleted.")

    else:
        print("Invalid method.")
User created.