Binary Data Abstractions
--
Boolean: Boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). 3.7
Boolean Value: A boolean value is either True or False. Variables with boolean values are often used to keep track of certain conditions within a program. 3.7
game_active = True
can_edit = False
Unicode: International character encoding standard that includes different languages, scripts and symbols. Each letter, digit or symbol has its own unique Unicode value. Unicode is an extension of ASCII that allows many more characters to be represented.
RGB: RGB (red, green, and blue) refers to a system for representing the colors to be used on a computer display. Red, green, and blue can be combined in various proportions to obtain any color in the visible spectrum.
Variables: A value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instruction s that tell the computer what to do and data that the program uses when it is running. 3.4
# in this case x and you are the variables
x = 7
y = 9
print(y + x)
Data Types: A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error.
Assignment Operators: operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands. 3.11
a = 3
b = 5
c = a + b
# Output
print(c)
Managing Complexity with Variables
--
Lists: A list is a sequence of several variables, grouped together under a single name. Instead of writing a program with many variables. 3.8
# make a list
letters = ['a', 'b', 'c']
# get the first item in the list
first_letter = letters [0]
# get last item in the list
last_letter = letters [-1]
# looping the list
for letter in letters:
print(letter)
# adding items to the list
letters = []
letters.append('a')
letters.append('b')
letters.append('c')
# numbered lists
squares = []
for x in range (1,11):
squares.append(x**2)
# list comprehensions
squares = [x**2 for x in range(1,11)]
# slicing the list
letters = ['a', 'b', 'c', 'd']
first_two = letters[:2]
# copy a list
copy_of_letters = letters[:]
Dictionaries: Python dictionaries allow you to connect pieces of related information. Each piece of information in a dictionary is stored as a key-value pair. When you provide a key, Python returns the value associated with that key. You can loop through all the key-value pairs, all the keys, or all the values.
# making a dictionary
ball = {'color': 'green', 'points': 5}
Looping Through a Dictionary: You can loop through a dictionary in three ways: you can loop through all the key value pairs, all the keys, or all the values. A dictionary only tracks the connections between keys and values; it doesn't track the order of items in the dictionary. If you want to process the information in order, you can sort the keys in your loop.
fav_language = {
'a': 'python',
'b': 'c',
'd': 'java',
'e': 'python',
}
# show each person's fav language
for name, language in fav_languages.items():
print(name + ":" + language)
Class: a template definition of the method s and variable s in a particular kind of object . Thus, an object is a specific instance of a class; it contains real values instead of variables. The class is one of the defining ideas of object-oriented programming.
class MY:
x = 5
Algorithms: a procedure or formula used for solving a problem. It is based on conducting a sequence of specified actions in which these actions describe how to do something, and your computer will do it exactly that way every time. An algorithm works by following a procedure, made up of inputs. 3.4
List = [1, 2, 3, "A", 2.3]
print(List)
Sequence: A set of logical steps carried out in order. Computers need instructions in the form of an algorithm in order to complete a desired task, and this algorithm must have the correct order of steps, or sequence. 3.4
Selection: Selection is a decision or question. At some point, a program may need to ask a question because it has reached a step where one or more options are available. Depending on the answer given, the program will follow a certain step and ignore the others.
Iteration: a sequence of instructions or code being repeated until a specific end result is achieved. Iterative development is sometimes called circular or evolutionary development. 3.10
Expressions: a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything. 3.2
Comparison Operators: operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== . Logical operators — operators that combine multiple boolean expressions or values and provide a single boolean output. 3.7
a = 3
b = 1
c = 2
if ( a == b ):
print ("1 - a is equal to b")
else:
print ("1 - a is not equal to b")
if ( a != b ):
print ("2 - a is not equal to b")
else:
print ("2 - a is equal to b")
if ( a < b ):
print ("4 - a is less than b")
else:
print ("4 - a is equal to b")
if ( a > b ):
print ("5 - a is greater than b")
else:
print ("5 - a is not greater than b")
if ( a <= b ):
print ("6 - a is either less than or equal to b")
else:
print ("6 - a is neither less than nor equal to b")
if ( b >= a ):
print ("7 - b is either greater than or equal to b")
else:
print ("7 - b is neither greater than nor equal to b")
Truth Tables: a breakdown of all the possible truth values returned by a logical expression. A truth value is typically either true or false, or 1 or 0. In some cases, the value might be based on another binary system, such as on and off or open and closed, but these are not as common. 3.11
Characters: a character is a display unit of information equivalent to one alphabetic letter or symbol. 3.4
a = "Hello, World!"
print(a[1])
Strings: an array of characters. The informal view of a string is a sentence. Strings are almost always written in code as a quoted sequence of characters, i.e., "this is a string". 3.4
print("Hello")
print('Hello')
Length: a code which maps source symbols to a variable number of bits. Variable-length codes can allow sources to be compressed and decompressed with zero error (lossless data compression) and still be read back symbol by symbol. 3.8
num_responses = len(fav_languages)
Traversing Strings: accessing all the elements of the string one after the other by using the subscript. A string can be traversed using for loop or while loop. 3.8
string_name = "luna"
# Iterate over the string
for element in string_name:
print(element, end=' ')
print("\n")
# Code #2
string_name = "LUNA"
# Iterate over index
for element in range(0, len(string_name)):
print(string_name[element])
Python
--
Conditionals with Lists: You can easily test weather a certain value is in a list. You can also test weather a list is empty before trying to loop through the list. 3.6
>>> players = ['a', 'b', 'c', 'd']
>>> 'a' in players
True
>>> 'e' in players
False
# testing if value is not in a list
banned_users = ['a', 'b', 'c']
user = 'd'
if user not in banned_users:
print("We have no players yet")
# checking if list is empty
players = []
if players:
for players in players:
print("Player: " + player.title())
else:
print("We have no players yet")
if: a programming conditional statement that, if proved true, performs a function or displays information. If statements are used to test for particular conditions and respond appropriately. 3.4
# age number
age = 19
# if statement
if age >= 18:
print("you are old enough to vote")
elif: used in conditional statements (if statements), and is short for else if 3.5
else conditionals: specifies a new condition if the first condition is false 3.5
age = 17
if age >= 18:
print("You are old enough to vote")
else:
print("You can't vote yet")
If, Else, Elif: 3.5
if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else:
ticket_price = 15
# age number
age = 12
# if statement
if age < 4:
price = 0
# elif statement
elif age < 18:
price = 5
# else statement
else:
price = 10
# final print
print("Your total cost is $" + str(price) + ".")
Nested Selection Statements: used when more than one decision must be made before carrying out a task. Nesting is a programming activity, in which one program block is placed inside other program block of the same operation type.
While Loops: A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10". 3.3
While loops with range: the range() method and returns a sequence of numbers starting from 0 by default and increments of 1. 3.2
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# user quit
# prompt that is given to the user
prompt = "\nTell me something, and I'll"
prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program"
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
# using continue in a loop
banned_users = ['a', 'b', 'c', 'd']
prompt = "\nAdd a player to your team"
prompt += "\nEnter 'quit' when you are done"
players = []
while True:
player = input(prompt)
if player == 'quit':
break
elif player in banned_users:
print(player + "is banned")
continue
else:
players.append(player)
print("\nYour Team:")
for player in players:
print(player)
While loops: A while loop repeats a block of code as long as a certain condition is true 3.2
# simple loops
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
# let the user choose when to quit
message = ''
while message != 'quit':
message = input("What's your message?")
print(message)
Combining loops with conditionals to break:
# using break to exit a loop
prompt = "\nWhat room are in in?"
prompt += "\nEnter 'quit' when you are done"
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'm in the" + room + "!")
Abstraction: the practice of hiding the details of how a particular code or system works and exposing only the essential features or functions that are necessary for other parts of the program to use 3.13
Procedures: is a named set of instructions that can take in parameters and return values. [may be called "method" or "function" in different programming languages] 3.12
Parameters: are independent variables used in the procedure to produce a result. It allows a procedure to execute without initially knowing specific input values. [can be classified as sequencing, selection, and iteration] 3.12
Return Values: calling script or function when it completes its task
append(): adding element to the end of the list
names = ['taiyo', 'ethan', 'parav', 'nikhil']
# add element to the end of the list
names.append('luna')
# start with empty list
names = []
names.append('taiyo')
names.append('ethan')
names.append('parav')
names. append('nikhil')
insert(): add an element in a specific position
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# adding in a specific position
names.insert(0, 'taiyo')
names.insert(3, 'ethan')
remove(): remove an item from the list
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# deleting by value
names.remove('parav')
# by position
del names[-1]
pop(): takes the item off the top of the "stack" (by default it returns the last element of the list but you can also op from any position)
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# pop last item of list
most_recent_name = names.pop()
print(most_recent_name)
# pop first item of list
first_name = names.pop(0)
print(first_name)
len(): returns the number of items in a list
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# find length of list
num_names = len(names)
print("There are" + str(num_names) + "names.")
sort(): changes oder of the list permanently
sorted(): returns a copy of the list which leaves the original copy unchanged
# sorted()
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# sort permanently
names.sort()
# sort permanently in reverse alphabetical order
names.sort(reverse=True)
# temp. sort
print(sorted(names))
print(sorted(names, reverse=True))
# reversing the order of a list
names.reverse()
range(): used to work with numbers efficiently
# print numbers 0 to 10
for number in range(11):
print(number)
# making list of numbers 1 to 10
# using the list() value can generate a large list of numbers
numbers = list(range(1, 10))
min(): finds the least value in a list
nums = [10, 30, 40, 60, 70, 60]
least = min(nums)
print(min(nums))
max(): finds the highest value in list
nums = [10, 30, 40, 60, 70, 60]
highest = max(nums)
print(max(nums))
sum(): sum of all in list
nums = [10, 30, 40, 60, 70, 60]
total = sum(nums)
print(sum(nums))
Libraries
--
seed(): initialize the random number generator
import random
random.seed(10)
print(random.random())
getstate(): returns the current internal state of the random number generator
import random
# remember this state
state = random.getstate()
# print 10 random numbers
print(random.sample(range(20), k = 10))
# restore state
random.setstate(state)
# print same first 5 random numbers
# as above
print(random.sample(range(20), k = 5))
setstate(): restores the internal state of the random number generator
import random
#print a random number:
print(random.random())
#capture the state:
state = random.getstate()
#print another random number:
print(random.random())
#restore the state:
random.setstate(state)
#and the next random number should be the same as when you captured the state:
print(random.random())
getrandbits(): returns a number representing the random bits
import random
print(random.getrandbits(8))
randrange(): returns a random number between the given range
import random
print(random.randrange(3, 9))
randint(): returns a random number between the given range
import random
print(random.randint(3, 9))
choice(): returns a random element from the given sequence
import random
mylist = ["apple", "banana", "cherry"]
print(random.choice(mylist))
choices(): returns a list with a random selection from the given sequence
import random
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, weights = [10, 1, 1], k = 14))
shuffle(): takes a sequence and returns the sequence in a random order
import random
mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist)
print(mylist)
sample(): returns a given sample of a sequence
# import random
from random import sample
# Prints list of random items of given length
list = [1, 2, 3, 4, 5]
print(sample(list,3))
random(): returns a random float number between 0 and 1
uniform(): returns a random float number between two given parameters
import random
# initializing bounds
a = 4
b = 9
# printing the random number
print("The random number generated between 4 and 9 is : ", end ="")
print(random.uniform(a, b))
betavariate(): return a random float number between 0 and 1 based on the Beta distribution (used in statistics)
import random
# determining the values of the parameters
a = 5
b = 10
# using the betavariate() method
print(random.betavariate(a, b))
expovariate(): returns a random float number based on the Exponential distribution (used in statistics)
import random
# determining the values of the parameter
num = 1.5
# using the expovariate() method
print(random.expovariate(num))
gammavariate(): Returns a random float number based on the Gamma distribution (used in statistics)
import random
# determining the values of the parameter
a = 100
b = 2
# using the gammavariate() method
print(random.gammavariate(a, b))
gauss(): Returns a random float number based on the Gaussian distribution (used in probability theories)
import random
# determining the values of the parameters
a = 100
b = 50
# using the gauss() method
print(random.gauss(a, b))
lognormvariate(): Returns a random float number based on a log-normal distribution (used in probability theories)
import random
# determining the values of the parameters
a = 0
b = 0.25
# using the lognormvariate() method
print(random.lognormvariate(a, b))
normalvariate(): Returns a random float number based on the normal distribution (used in probability theories)
import random
# determining the values of the parameters
a = 100
b = 50
# using the normalvariate() method
print(random.normalvariate(a, b))
vonmisesvariate(): Returns a random float number based on the von Mises distribution (used in directional statistics)
import random
# determining the values of the parameters
a = 0
b = 4
# using the vonmisesvariate() method
print(random.vonmisesvariate(a, b))
paretovariate(): Returns a random float number based on the Pareto distribution (used in probability theories)
import random
# determining the values of the parameter
a = 3
# using the paretovariate() method
print(random.paretovariate(a))
weibullvariate(): Returns a random float number based on the Weibull distribution (used in statistics)
import random
# determining the values of the parameters
a = 1
b = 1.5
# using the weibullvariate() method
print(random.weibullvariate(a, b))