1/249
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Low level programming language
a programming language that is closer to how the processor thinks and hardware (machine code), are quite difficult to learn (EX. C)
High level programming language
a language where the code you write is more abstract from the machine code that it produces (EX. Python); enables development of a program in a much more user-friendly programming context
Version Control System
powerful tools that enable you to track changes to programming projects; enable you to look back at your code at any point in time in the past, collaborate with other developers and merge the work of many into a working product
Repository (Repo)
the place where a project lives
Commit
an incremental change to the repository
Origin
the location of the remote repository
Master
the name of the default branch in the git repository
Branches
in Git allow you to work on specific features independently, without touching the code in master
Types:
*The master branch
*The dev branch
Master Branch
the production state of your application.
Dev Branch
the testing state of your application, which would be what you test on
Pull request (pr)
allow you to review all the code that would be changed in the merge and either approve or reject it.
script.py
the filename of the Python program you want to run
Variables
a way of storing data in programs; the act of assigning a value where we use the equals (=) operator.
String
A series of characters (basically, text); are always surrounded by quotes
Integer
A whole number (could be positive or negative)
Float
A number with a decimal point
Boolean
A True or False value; can be represented as 1 (True) and 0 (False)
"Whitespace"
refers to a type of character that doesn't print anything out, but adds some sort of spacing formatting to the output.
\n character combination
tell the program where we want our line breaks
\t character combination
can add tabs to our output
lstrip()
can strip whitespace off the left side of a string
email = ' jane@email.com '
email.lstrip()
Output: "jane@email.com "
rstrip()
can strip whitespace off the right side of a string
email = ' jane@email.com '
email.rstrip()
Output: " jane@email.com"
strip()
strip both sides of a string at the same time
email = " jane@email.com "
email.strip()
Output: "jane@email.com"
print()
program will output the result of a string/mathematical operator
round() function
it rounds decimal numbers up or down, to a given preferred decimal place
Lists
a list of things stored in a particular order
(EX. fav_linux_distros = ['Mint', 'Debian', 'Ubuntu']
Index of -1
Python will always return the last item in the list
(EX. print(fav_linux_distros[-1]) )
upper() function
modified an item from our list to appear in all uppercase
(EX. top_fav_distro.upper() )
len() function
get a quick count of the things in our list
(EX. print(len(fav_linux_distros)) )
sort() function
sorts a list alphabetically
(EX.
fav_linux_distros = ['Mint', 'Debian', 'Ubuntu', 'Manjaro', 'Fedora', 'Arch']
fav_linux_distros.sort()
Output: ['Arch', 'Debian', 'Fedora', 'Manjaro', 'Mint', 'Ubuntu'] )
reverse() funtcion
reverse the order of a list
(EX.
fav_linux_distros = ['Mint', 'Debian', 'Ubuntu', 'Manjaro', 'Fedora', 'Arch']
fav_linux_distros.reverse()
Output: ['Ubuntu', 'Mint', 'Manjaro', 'Fedora', 'Debian', 'Arch'] )
append() function
allows us to stick items onto the end of a list.
(EX. travel_bucket_list.append('Toronto') )
insert() fucntion
add items into an existing list at any position we want
(EX. travel_bucket_list.insert(0, 'New York') )
pop() fucntion
taken the last item from the list and "popped" it off
(EX. visited = travel_bucket_list.pop() )
remove() function
will allow us to remove an item from our list without specifying an index
(EX. travel_bucket_list.remove('Hawaii') )
Tuples
similar to lists, except for 1 important quality: they are immutable; content items in the list can't be changed once they are set.
(EX. stonehenge = ('51.1739726374', '-1.82237671048') )
Dictionaries
in Python is similar to a list in that it's a collection of "things" we can store together; in which that information is stored and retrieved
(EX. case_stats = {'total': 21, 'solved': 12, 'unsolved': 8} )
Code Comments
are pieces of information you put in the code that the computer ignores; allows us to add notes and narration into our code without having to worry about syntax, to help make it clear to ourselves - and to others - what our program is intended to do
(EX.
# Say hello to the user
print("Hello User!") )
Conditionals
allows us to check if certain conditions are being met before we run certain parts of the program; often referred to more casually as "if statements" or "if tests"
lower() fucntion
takes a string and changes any uppercase letters it finds within the string to their lowercase counterparts
(EX. drink_available.lower() )
if-else block
allows us to create a diverging path of instructions, depending on the outcome of our check
(EX.
if coffee_available == True:
print("Agent J will have coffee.")
else:
print("Sorry Agent J, our coffee has run out!") )
elif check
allows us to have a second set of checks we run if statement and the first checks fail
(EX.
if coffee_available == True and (had_coffee_already == False or is_tired == True):
print("Agent J will have coffee.")
elif coffee_available == False:
print("Sorry Agent J, our coffee has run out!") )
Loops
can run the same operation on multiple items in a list.; take the list as it is, and do something over and over for each item until it runs out of items
(EX.
for distro in fav_linux_distros:
print(distro) )
range() function
allows us to create a temporary 'list' of numbers within a specified range, which we can then loop through similar to a normal for loop.
(EX.
for counter in range(1,5):
print(counter) )
values() fucntion
only asking the computer to grab the values it finds for each key, and to not worry about what the key is.
(EX.
for distro in fav_distros.values():
print(distro) )
While Loops
as long as that condition is true, the loop will keep running
(EX.
while counter <= 3:
print(counter)
counter += 1 )
Functions
allow us to split our code apart into smaller chunks that we can call on at any point in our program
(EX.
def greet_agent():
print('Hello Agent J!')
greet_agent() )
Function Pararmeters
lets us pass information into our function at the time we call it, then have the function use that information within it when it executes
(EX.
def greet_agent(letter):
print('Hello Agent ' + letter + '!')
greet_agent('J') )
Single Responsibility Principle
A good rule of thumb for functions is they should only do 1 thing
raw_input() function
will interpret everything the user feeds into it as a string, no matter what characters are typed; if the user provides a number - like 42 - this will be interpreted as the string '42'
(EX. user_name = raw_input('Hello, what is your name? ') )
input() function
allows us to incorporate user input into a program; tries to figure out the intended type of the user input: it wants to interpret 42 as the integer 42
eval() function
it will evaluate what is passed to it as code; a user could hypothetically type a function definition and a function call into the space we've provided for user input
isdigit() function
allows us to check if the string the user provided can be turned into an integer.
(EX.
if user_input.isdigit():
user_input_int = int(user_input) )
get_reply() function
determines if the user's input can be used in the way we want using the isdigit() method
(EX.
# Process the answer to get the right reply, and print that reply
reply = get_reply(user_coffee_input)
print(reply)
Class
create a model of a real-world thing, and then uses that as a kind of template to create objects from; we define the general way an object is constructed and how it behaves
(EX.
class Agent():
name = '' . . . )
Object
a little self-contained "thing" that has all the attributes and methods associated to it that we defined in our class; as an instance of a class
(EX.
agent_q = Agent() )
Self arguement
refers to itself - the object the class creates;
*By calling self.name and self.hot_drink within our methods, we're telling the methods to look outside the method itself, but stay within the class when trying to find the variables name and hot_drink
speak() function
how each arguement/function talks to each other in a program
(EX.
agent_q.speak("Hi, I'm Agent Q!")
agent_m.speak("Hi, nice to meet you. I'm Agent M.") )
Object Constructors
will let us both instantiate our class and assign our key attributes all on 1 line; stated as _init_()
(EX.
def __init__(self, name, hot_drink):
self.name = name )
Traceback Error
they give us additional information about what went wrong in our code
(EX.
Traceback (most recent call last):
File "program.py", line 1, in <module>
print(5/0)
ZeroDivisionError: integer division or modulo by zero )
Exception
Whenever an error happens, Python creates an exception object and, by default, halts the execution of the program as soon as the exception is generated
Try-catch block
handle exceptions that we suspect might crop up in our code
(EX.
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
read() function
will go into the file and get all the content to a new value to be read from
(EX.
with open('file.txt') as file:
content = file.read()
print(content)
write() function
allows us to write content to a file.txt from python
(EX.
with open('file.txt', 'a') as file:
file.write("\nHello, I'm some text inside a file.")
open() function
opens a .txt file from the python command prompt, opens and exsisting or newly created file
(EX.
with open('file.txt') as file:
Socket
allows us to make and receive network connections
socket.AF_INET argument
this socket is going to use IPv4 and not IPv6 or, say, Bluetooth
*For IPv6 we would use socket.AF_INET6
(EX.
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.SOCK_STREAM argument
how we tell the socket to use the TCP protocol and not the UDP protocol
*you wanted to make a UDP connection, you could use socket.SOCK_DGRAM
(EX.
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect() function
we initiate a connection with our socket
(EX. client_socket.connect(('127.0.0.1', 1337)) )
send() function
send some data over the connection; send a byte object; TCP
(EX. client_socket.send(b"Do you want to play a game?\n") )
byte object
a binary representation of the string, this is what the b before the quotations comes in; to convert that string into a byte object
recv() function
storing the return value of this in the variable received; maximum number of bytes we'll allow at once
(EX. received = client_socket.recv(1024) )
close() function
close the connection
(EX. client_socket.close() )
bind() function
allows our program to take ownership of the IP address and port number in the tuple we pass in as an argument, if it's not being used by any other program
(EX. server_socket.bind(("0.0.0.0", 1337)) )
listen() function
it allows the server to listen on the port it has bound to; TCP
(EX. server_socket.listen(10) )
accept() function
establish a connection with a client; TCP
* When we accept a new connection successfully, send the string "Do you want to play a game?\n" and then wait for a reply
(EX. conn, addr = server_socket.accept() )
sendto() function
forces us to send the tuple containing the IP address and port number along with every message; UDP
(EX.
client_socket.sendto(b"UDP is connectionless...\n", ("127.0.0.1", 1337)) )
recvfrom() function
takes a maximum number of bytes allowed to be sent: in this case, 1024 bytes; UDP
(EX.
while True:
data, addr = server_socket.recvfrom(1024)
print(data) )
handler() function
accepts a socket object and an address as parameters
(EX. def handler(client_sock, address): )
repr() function
information stored in address at this time will be a tuple. In order to print out the content of a tuple, we first have to transform it into a string, which we can do with repr()
(EX. print(repr(address) + " connection ended.")
thread.start_new_thread() function
creates a new thread
(EX. _thread.start_new_thread(handler, (client_sock, address))
port scanner
a tool that will try to connect to ports on a target system and report back about which ones are open or not
connect_ex() function
return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as "host not found," can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable
Documentation in python
lists out the standard provided objects, functions, and methods, as well as the parameters they accept and the values they return
(EX.
mainuser@ubuntu:~$ python
Python 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0] on linux
Type "help","copyright", "credits" or "license" for more information.
quit() function
exit out of Python interactive
(EX.
>>> quit()
mainuser@ubuntu:~$
pow() function
raises a number to a power
(EX.
>>> pow(2, 18)
262144
math.pow() function
it converts both of the arguments it receives to floats (remember, these are numbers with a decimal point)
(EX.
>>> math.pow(2, 18)
262144.0
consistency
use of the same principles and code language that is easier for you to use in programming; have to bend or break our own personal style rules when we work on someone else's code or work with a team
Defensive programming
a way of programming that tries to expect the unexpected, in order to prevent bugs and unexpected behaviour from occurring.
assert function
cause the program to crash with the error message we provided if a condition is not met
(EX.
def no_negatives(number):
assert number >= 0, 'negative value passed to the no_negatives() function!'
print(number)
Procedural programming
the paradigm that new programmers tend to gravitate toward, and is most often represented in beginner tutorials and guides; step-by-step programming level
Object-oriented programming
uses classes to model objects, capturing both their attributes - the data that describes them - and their methods - the behaviours they have; more complex
User() object
object would know everything about the user, such as their name, their email address, their account creation date and time, and their password
Pseudocode
a way of starting to think like a programmer but without worrying about syntax or the details around making real code work
stdio library
a standard C library for dealing with input and output. The name stands for "standard input output"
(EX. #include <stdio.h> )
int main() function
tells us that the main function takes no parameters and returns an integer value
(EX. int main() { puts("Hello, World!"); return(0); } )
puts() function
stands for "put string", and it takes just one parameter: the string to output.
(EX.
puts(variable_1);
puts("and a space "); )
char array
a variable with a type that can store 'strings'. This means we can use something stored in memory once multiple times
(EX. char variable_1[] = "Hello my first variable"; )
printf()
the ability to handle multiple output streams, different data types and even convert a given type to a different format
(EX. printf("Your username is %s \n", username); )
%s
insert a string here
(EX. printf("Your username is %s and you are %d years old\n", username, age); )