Observations: - In a program, a variable is an abstraction that retains a value. Each variable is paired with data storage that can only hold one value at a time (However, if the value is a collection type such as a list, then the value can contain multiple values). Variables can be thought of as "containers," and each one has a name that describes what it is meant to hold.

  • Depending on what is being represented, variables have a variety of data types that hold particular types of data.

Hacks 1

Questions (College Board's Essential Knowledge):

  1. What exactly IS a variable?
  • A variable is an abstraction that stores a value inside of a program, and each variable has a corresponding data storage that holds just one value at a time
  1. What is the best data type to represent someone's dog's name?
    • The best data type is a string
  2. Why is it important to give variables specific names before containing values?
    • In order for them to have a name that is appropriate for the value that will be contained.
  3. What is the best way to represent someone's phone number?
    • The best way to ensure that the numbers don't obstruct the code is to use a string.

Bonus (Not required but important to know):

  1. How can we update a variable's value
    • To update a variable's value u can do it using + or - for incrementing or decrementing
  2. What function is used to receive a user's input?
    • input()

Hacks 2

Answer these:

  1. In your own words, briefly explain by writing down what an assignment operator is
    • The equal sign (=) serves as the assignment operator and enables the assignment of code elements to values.
  2. In Collegeboard pseudocode, what symbol is used to assign values to variables?
    • <--
  3. A variable, x, is initially given a value of 15. Later on, the value for x is changed to 22. If you print x, would the command display 15 or 22?
    • It would display 22.

Hacks 3

  1. What is a list?
    • a series of elements, each of which is a variable.
  2. What is an element
    • An element are the items inside of a list.
  3. What is an easy way to reference the elements in a list or string?
    • using print()
  4. What is an example of a string?
    • Hello World
  • Create a list with indices
  • Index a part of the list that you created.
  • Try to index from the end
NamesList = ["Nikhil", "Taiyo", "Lunda", "Parav", "Ethan"]
print(NamesList[2])
print(NamesList[4])
Lunda
Ethan
num1=input("Input a number. ")
num2=input("Input a number. ")
num3=input("Input a number. ")
add=input("How much would you like to add? ")

# Add code in the space below

numlist = [int(num1), int(num2), int(num3)]
print("User submitted numbers", numlist)
print("Plus " + add)

# The following is the code that adds the inputted addend to the other numbers. It is hidden from the user.

for i in range (len(numlist)):
    numlist[i-1] += int(add)

print("Result: ", numlist)
User submitted numbers [1, 2, 3]
Plus 4
Result:  [5, 6, 7]
foodlist = ["eggs", "bread", "chicken", "rice", "pizza"]
print(foodlist)
['eggs', 'bread', 'chicken', 'rice', 'pizza']
import getpass, sys

def question_with_response(prompt):
    print("Question: " + prompt)
    msg = input()
    return msg

questions = 3
correct = 0

print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_with_response("Are you ready to take a test?")

rsp = question_with_response("The purpose of lists and dictionaries are to manage the ____ of a program")
if rsp == "complexity":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

rsp = question_with_response("Lists are a form of data ______")
if rsp == "abstraction":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

rsp = question_with_response("Which brackets are used to assign values to a variable to make a list?")
if rsp == "[]":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!") 

print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))
Hello, nikhilchakravarthula running /Users/nikhilchakravarthula/opt/anaconda3/bin/python
You will be asked 3 questions.
Question: Are you ready to take a test?
Question: The purpose of lists and dictionaries are to manage the ____ of a program
complexity is correct!
Question: Lists are a form of data ______
abstraction is correct!
Question: Which brackets are used to assign values to a variable to make a list?
[] is correct!
nikhilchakravarthula you scored 3/3

Lesson 3 & 4 Hacks

Notes: An algorithm is a sequential process that describes a set of instructions that must be followed in a specific order in order to produce the intended result. An algorithm provides the computer with a set of instructions that it can follow to complete any task. There are three components to an algorithm: sequencing, selection, and iteration. Similar to how you would follow a teacher's instructions, a sequence is the order in which something should be done in order to accomplish a goal. A loop, or iteration, occurs when something is repeated until a condition is met, such when you turn off your computer after finishing a task. Languages that utilize arithmetic operators include those that use addition, subtraction, multiplication, division, and modulus.

Hacks 1

Sequencing: 1,2,5 Selection: 3 Iteration: 4

Hacks 2

num1 = 5
num2 = num1 * 3
num3 = num2 / num1 * (9 % 2) * 4
result = (num3 % num1 + num2) % num3 * 3 / 5

print(result)
3.0

Crossword Puzzle

Down: 1) iteration 2) selection

Across: 3) sequence

Hacks 5-6

Explain in your own words what each logical operator does.

  • Not: This displays the opposite of the data inputed.
  • And: This helps determine if the conditions are met
  • Or: This may help determine if one of the conditions is met.

Code your own scenario that makes sense for each logical operator

walking = True
result = not(walking)
print(result)
False
USD = 10
Coins = 100
if USD >= 9 and Coins >= 100:
    print("You have a lot of money")
else:
    print("you have less money")
You have a lot of money
Cars = 100
Ferrari = 2
if Ferrari >= 1 or Cars >= 101:
    print("you have good cars")
you have good cars

1 point for defining all the key terms in your own words. 0.5 points if you use examples that show you truly understand it.

  • Selection: This is a piece of code that is determined if the ouput is true or false.
  • Algorithm: An algorithm is a process and a set of rules that should be followed when doing calculations.
  • Conditional statements: These are a set of rules to see if a condition is met.

1 point for writing a program that uses binary conditional logic. 0.5 points if it is original and shows complexity

x = int(input("choose a number"))
if x % 2 == 0:
    print(x, "is even")
else:
    print(x, "is odd")
12 is even

Hacks section 9-11

Notes

First, create algorithms.

Outlining an algorithm's procedure before coding is a smart idea. This guarantees that it is correctly sequenced. You should use a flowchart or simple language to represent the algorithm. You can use visualization to more clearly observe how the entire algorithm works. This might make the coding process more productive and efficient.

2) Evaluation of Iteration and Selection

Iterative algorithms repeat a function until a target is reached. We can use iteration to more simply represent an algorithm without illustrating all the repeated steps. Algorithms with selection only execute specific functions in the case of certain conditions being true or false.

3) Why are algorithms used?

It is simple to think that two algorithms that look quite similar do the same task. That is not the case, though, because we have learned to detect minute variations in code and essentially debug.

isCold = True
isHot = False

if isCold == True:
    print(" Jacket necessary!")

elif isHot == True:
    print("No Jacket necessary!")
 Jacket necessary!
isCold = False
isHot = True

puddles = not(isCold) and isHot
if isHot == False:
    print("No Jacket!")
elif isCold == True:
    print("Jacket!")

1) When the code first runs, there are 5 coins available.

2) The AmountMoney variable is set to True.

3) $1 is subtracted from the coins variable but AmountMoney stays true.

4) The string "Broke!" is printed when the variable coins reaches a value of 0. At that point, AmountMoney is set to False.

5) End!

Coins = 10
AmountMoney = True
while(AmountMoney == True):
    Coins -= 1
    if Coins == 0:
        AmountMoney == False
        print("Broke")
    
Broke
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
/Users/nikhilchakravarthula/vscode/Blog1/_notebooks/2022-11-30-Hacks.ipynb Cell 24 in <cell line: 3>()
      <a href='vscode-notebook-cell:/Users/nikhilchakravarthula/vscode/Blog1/_notebooks/2022-11-30-Hacks.ipynb#X34sZmlsZQ%3D%3D?line=0'>1</a> Coins = 10
      <a href='vscode-notebook-cell:/Users/nikhilchakravarthula/vscode/Blog1/_notebooks/2022-11-30-Hacks.ipynb#X34sZmlsZQ%3D%3D?line=1'>2</a> AmountMoney = True
----> <a href='vscode-notebook-cell:/Users/nikhilchakravarthula/vscode/Blog1/_notebooks/2022-11-30-Hacks.ipynb#X34sZmlsZQ%3D%3D?line=2'>3</a> while(AmountMoney == True):
      <a href='vscode-notebook-cell:/Users/nikhilchakravarthula/vscode/Blog1/_notebooks/2022-11-30-Hacks.ipynb#X34sZmlsZQ%3D%3D?line=3'>4</a>     Coins -= 1
      <a href='vscode-notebook-cell:/Users/nikhilchakravarthula/vscode/Blog1/_notebooks/2022-11-30-Hacks.ipynb#X34sZmlsZQ%3D%3D?line=4'>5</a>     if Coins == 0:

KeyboardInterrupt: 

Hacks for 3.9.3

import random

num_guesses = 0
user_guess = -1
upper_bound = 100
lower_bound = 0

number = random.randint(0,100)


print(f"I'm thinking of a number between 0 and 100.")

def guess():
    num = input("Input your guess")
    return num 

def search(number, guess):
    global lower_bound, upper_bound
    if int(guess) < int(number):
        print("Too low, try again!!!!") 
        lower_bound = guess
        return lower_bound, upper_bound
    elif int(guess) > int(number):
        print("Too high, try again!!!!! ") 
        upper_bound = guess
        return lower_bound, upper_bound
    else:
        upper_bound, lower_bound = guess, guess
        return lower_bound, upper_bound 

while user_guess != number:
    user_guess = guess()
    num_guesses += 1
    print(f"You guessed {user_guess}.")
    lower_bound, upper_bound = search(number, user_guess)
    if int(upper_bound) == int(number):
        break
    else:
        print(f"Guess a number between {lower_bound} and {upper_bound}.")


print(f"You guessed the number in {num_guesses} guesses!")
I'm thinking of a number between 0 and 100.
You guessed 30.
Too low, try again!!!!
Guess a number between 30 and 100.
You guessed 72.
Too low, try again!!!!
Guess a number between 72 and 100.
You guessed 91.
Too high, try again!!!!! 
Guess a number between 72 and 91.
You guessed 83.
Too high, try again!!!!! 
Guess a number between 72 and 83.
You guessed 75.
Too high, try again!!!!! 
Guess a number between 72 and 75.
You guessed 73.
Too low, try again!!!!
Guess a number between 73 and 75.
You guessed 74.
You guessed the number in 7 guesses!

Answer is in image below

Answer: Set 1: 80, Set 2: 74, Set 3: 96

Answer is C

numListOne = [12,14,44,57,79,80,99]
numListTwo = [92,43,74,66,30,12,1]
numListThree = [7,13,96,111,33,84,60]
numLists = [numListOne, numListTwo, numListThree]
for x in range(len(numLists)):
    numLists[x].sort()
    middle = int(len(numLists[x])/2)
    print("Middle Index of List #",x+1,"is",numLists[x][middle])
Middle Index of List # 1 is 57
Middle Index of List # 2 is 43
Middle Index of List # 3 is 60

Lesson 12-13 hacks

a) Procedure: A block of code that is created to perform a given task - essentially a function.

b) Parameter: A variable that is utilized in a function that enables data to be imported into said function.

a) A return value is a value that a function or method returns to the caller code once it has completed executing. Once the function or method has completed its task, the value is returned to the caller code.

b) Output parameters, which are variables supplied by reference to a function or method and used to return a value to the caller code, are another type of parameter. They are frequently used to have a single function or method return a number of values.

import math

userNum = float(input())

def sqrt(userNum):
    return userNum

sqrt = math.sqrt(userNum)
print("Square root of", userNum , ":", float(sqrt))  
Square root of 10.0 : 3.1622776601683795

Hacks 2

x = 20
y = 100

# Set function
def addition(x,y):
    sum = x + y
    return(sum)

#Print the result
print(addition(x,y))
120
def split_string(s):
    # use the split() method to split the string into a list of words
    words = s.split(" ")

	# initialize a new list to hold all non-empty strings
    new_words = []
    for word in words:
        if word != "":
            # add all non-empty substrings of `words` to `new_words`
            new_words.append(word)
    
    return words

# this function takes a list of words as input and returns the number of words
# that start with the given letter (case-insensitive)
def count_words_starting_with_letter(words, letter):
    count = 0
    
    # loop through the list of words and check if each word starts with the given letter
    for word in words:
        # use the lower() method to make the comparison case-insensitive
        if word.lower().startswith(letter):
            count += 1
    
    return count

# this function takes a string as input and returns the number of words that start with 'a'
def count_words_starting_with_a_in_string(s):
    # use the split_string() function to split the input string into a list of words
    words = split_string(s)
    
    # use the count_words_starting_with_letter() function to count the number of words
    # that start with 'a' in the list of words
    count = count_words_starting_with_letter(words, "a")
    
    return count

# see above
def count_words_starting_with_d_in_string(s):
    words = split_string(s)
    count = count_words_starting_with_letter(words, "d")
    return count

# example usage:
s = "   This is  a  test  string! Don't you think this is cool? "
a_count = count_words_starting_with_a_in_string(s)
d_count = count_words_starting_with_d_in_string(s)
print("Words starting with a:", a_count)
print("Words starting with d:", d_count)
Words starting with a: 1
Words starting with d: 1

3.13 Hacks

x = 1 y = 2

<button id= “add” type=“button” onclick=“addition(x,y)“>addition</button>

<p id = “output”>

</p>

<button id= “subtract” type=“button” onclick=“subtraction(x,y)“>subtraction</button>

<p id = “output2”>

</p>

<button id= “divide” type=“button” onclick=“divide(x,y)“>divide</button>

<p id = “output3”>

</p>

<button id= “multiply” type=“button” onclick=“multiply(x,y)“>multiply</button>

<p id = “output4”>

</p>

Enter First Number:

Enter Second Number: