Skip to content

Instantly share code, notes, and snippets.

@peta909
Last active March 29, 2019 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peta909/c371336032442350fd484956fda34552 to your computer and use it in GitHub Desktop.
Save peta909/c371336032442350fd484956fda34552 to your computer and use it in GitHub Desktop.
Python code with comments
from math import *
import struct
'''
This is
Multi
Line
comment
'''
#-----------------------DATA STRUCTURES--------------------------
'''
{key: value, ...} for dict, #unordered
{value, value, ...} for sets, #immutable
[aa,bb,cc,...] for lists, #indexed
(1,3,4) for tuple, #immutable
'''
# LISTS -------------
# A list allows you to create a list of values and manipulate them
# Each value has an index with the first one starting at 0
def use_lists():
names = ["Rubble", "Skyle", "Chase", "Marshall", "Rocky", "Everest", "Zuma", "Tracker", "Ryder"]
veh_num = [1, 2, 3, 4, 5, 6, 7, 8]
print names.pop()
print names
print names.append(veh_num)
print names[4:5]
grocery_list = ['Juice', 'Tomatoes', 'Potatoes', 'Bananas']
print('The first item is', grocery_list[1])
# You can change the value stored in a list box
grocery_list[0] = "Green Juice"
print(grocery_list)
# You can get a subset of the list with [min:up to but not including max]
print(grocery_list[1:3])
# You can put any data type in a a list including a list
other_events = ['Wash Car', 'Pick up Kids', 'Cash Check']
to_do_list = [other_events, grocery_list]
print(to_do_list)
# Get the second item in the second list (Boxes inside of boxes)
print(to_do_list[1][1])
# You add values using append
grocery_list.append('onions')
print(to_do_list)
# Insert item at given index
grocery_list.insert(1, "Pickle")
# Remove item from list
grocery_list.remove("Pickle")
# Sorts items in list
grocery_list.sort()
# Reverse sort items in list
grocery_list.reverse()
# del deletes an item at specified index
del grocery_list[4]
print(to_do_list)
# We can combine lists with a +
to_do_list = other_events + grocery_list
print(to_do_list)
# Get length of list
print(len(to_do_list))
# Get the max item in list
print(max(to_do_list))
# Get the minimum item in list
print(min(to_do_list))
def use_tuples():
# TUPLES -------------
# Values in a tuple can't change like lists
pi_tuple = (3, 1, 4, 1, 5, 9)
# Convert tuple into a list
new_tuple = list(pi_tuple)
# Convert a list into a tuple
# new_list = tuple(grocery_list)
# tuples also have len(tuple), min(tuple) and max(tuple)
tuple1 = ("I", "am", "a", "tuple")
tuple2 = ("I", "immutable.")
list_tuples = [tuple1, tuple2]
print tuple1 + tuple2
print tuple2[1]
#tuple2[1] = "unchangeable" #This line throws an error as tuples unlike list they cant be changed!
print list_tuples
def use_dictionary():
# DICTIONARY or MAP -------------
# Made up of values with a unique key for each value
# Similar to lists, but you can't join dicts with a +
super_villains = {'Fiddler': 'Isaac Bowin',
'Captain Cold': 'Leonard Snart',
'Weather Wizard': 'Mark Mardon',
'Mirror Master': 'Sam Scudder',
'Pied Piper': 'Thomas Peterson'}
print(super_villains['Captain Cold'])
# Delete an entry
del super_villains['Fiddler']
print(super_villains)
# Replace a value
super_villains['Pied Piper'] = 'Hartley Rathaway'
# Print the number of items in the dictionary
print(len(super_villains))
# Get the value for the passed key
print(super_villains.get("Pied Piper"))
# Get a list of dictionary keys
print(super_villains.keys())
# Get a list of dictionary values
print(super_villains.values())
months = {
1:"Jan",
2:"Feb",
3:"Mar",
4: "Apr",
5: "May",
6: "Jun",
7: "Jul",
8: "Aug",
}
print months[2]
key = 11
print(months.get(key, "Cant be found"))#a default value can be returned if the key is not found
key = 3
print(months.get(key, "Cant be found")) # a default value can be returned if the key is not found
#--------------CODE FLOW ----------------------------------
def use_if_else():
if_big = 6
if if_big == 6:
print ("This is 6\n")
elif if_big == 5:
print( "This is 5\n")
else:
print ("I have no idea what this is\n")
def use_loops():
i = 3
for n in range(5, 10):
print n
print "for loops over"
while i < 10:
i += 1
if i == 6:
continue
elif i == 8:
break
print i
def conditionals():
# CONDITIONALS -------------
# The if, else and elif statements are used to perform different
# actions based off of conditions
# Comparison Operators : ==, !=, >, <, >=, <=
# The if statement will execute code if a condition is met
# White space is used to group blocks of code in Python
# Use the same number of proceeding spaces for blocks of code
age = 30
if age > 16:
print('You are old enough to drive')
# Use an if statement if you want to execute different code regardless
# of whether the condition ws met or not
if age > 16:
print('You are old enough to drive')
else:
print('You are not old enough to drive')
# If you want to check for multiple conditions use elif
# If the first matches it won't check other conditions that follow
if age >= 21:
print('You are old enough to drive a tractor trailer')
elif age >= 16:
print('You are old enough to drive a car')
else:
print('You are not old enough to drive')
# You can combine conditions with logical operators
# Logical Operators : and, or, not
if ((age >= 1) and (age <= 18)):
print("You get a birthday party")
elif (age == 21) or (age >= 65):
print("You get a birthday party")
elif not (age == 30):
print("You don't get a birthday party")
else:
print("You get a birthday party yeah")
# FOR LOOPS -------------
# Allows you to perform an action a set number of times
# Range performs the action 10 times 0 - 9
for x in range(0, 10):
# print(x , ' ', end="")
print(x)
print('\n')
# You can use for loops to cycle through a list
grocery_list = ['Juice', 'Tomatoes', 'Potatoes', 'Bananas']
for y in grocery_list:
print(y)
# You can also define a list of numbers to cycle through
for x in [2, 4, 6, 8, 10]:
print(x)
# You can double up for loops to cycle through lists
num_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]];
for x in range(0, 3):
for y in range(0, 3):
print(num_list[x][y])
# WHILE LOOPS -------------
# While loops are used when you don't know ahead of time how many
# times you'll have to loop
random_num = random.randrange(0, 100)
while (random_num != 15):
print(random_num)
random_num = random.randrange(0, 100)
# An iterator for a while loop is defined before the loop
i = 0;
while (i <= 20):
if (i % 2 == 0):
print(i)
elif (i == 9):
# Forces the loop to end all together
break
else:
# Shorthand for i = i + 1
i += 1
# Skips to the next iteration of the loop
continue
i += 1
def do_catch_error():
try :
value = 4 / 0
print value
except ZeroDivisionError:
print ("/0 error")
def use_files():
thisfile = open("readme.txt", "r+")
for line in thisfile.readlines():#readlines read each line into an array
print line
entry = ["more words","even more words\n"]
thisfile.writelines(entry)#writelines expects a list
print ("After write")
print(thisfile.read())
thisfile.close()
# FILE I/O -------------
# Overwrite or create a file for writing
test_file = open("test.txt", "wb")
# Get the file mode used
print(test_file.mode)
# Get the files name
print(test_file.name)
# Write text to a file with a newline
test_file.write(bytes("Write me to the file\n", 'UTF-8'))
# Close the file
test_file.close()
# Opens a file for reading and writing
test_file = open("test.txt", "r+")
# Read text from the file
text_in_file = test_file.read()
print(text_in_file)
# Delete the file
os.remove("test.txt")
#----------- Hex manipulations
def do_rotation():
import struct
# Rotate left: 0b1001 --> 0b0011
rol = lambda val, r_bits, max_bits: \
(val << r_bits % max_bits) & (2 ** max_bits - 1) | \
((val & (2 ** max_bits - 1)) >> (max_bits - (r_bits % max_bits)))
# Rotate right: 0b1001 --> 0b1100
ror = lambda val, r_bits, max_bits: \
((val & (2 ** max_bits - 1)) >> r_bits % max_bits) | \
(val << (max_bits - (r_bits % max_bits)) & (2 ** max_bits - 1))
value = 0xC000
i = 8 # no to rotate
max_bits = 32 # buffer size
print "rol", rol(value, i, max_bits)
value = 0x0003
print "ror", ror(value, i, max_bits)
# how-to-convert-integer-value-to-array-of-four-bytes-in-python
print [hex(0x12345678 >> i & 0xff) for i in (24, 16, 8, 0)]
# ['0x12', '0x34', '0x56', '0x78']
tup_result = struct.unpack("4b", struct.pack(">I", 0x12345678))
# result will be in a tuple
# note the Endianess ">"
list_result = list(tup_result)
print [hex(x) for x in list_result]
tup_result = struct.unpack("4b", struct.pack("<I", 0x12345678))
# result will be in a tuple
# note the Endianess "<"
list_result = list(tup_result)
print [hex(x) for x in list_result]
# rotate a 4 byte buffer
aa = bytearray(list_result)
int_result = struct.unpack('I', aa)[0]
int_result = ror(int_result, 8, 32)
tup_result = struct.unpack("4b", struct.pack("I", int_result))
result = list(tup_result)
print [hex(x) for x in result]
def use_hex_bytes():
a = "AA"
len(a)
Byte_hex = struct.unpack('2b',a)
print Byte_hex
print (type(Byte_hex))
for i in Byte_hex:
print hex(i)
print type(i)
a = struct.pack(">I", 0x41414141)
print a
print type(a)
def hex_dump():
# try to write a simple hex dump
import binascii, struct
fd = open("abcd.exe", "r")
fd_contents_str = fd.read()
fd_contents_hex = (binascii.b2a_hex(fd_contents_str)).upper()
Hex_dump = []
Byte_str = ""
for i, Half_byte in enumerate(fd_contents_hex):
Byte_str = Byte_str + Half_byte
if i % 2:
Byte_hex = struct.unpack('2b', Byte_str) # "4D" converted into (52,68)
Hex_dump.append(Byte_hex)
Byte_str = ""
print Hex_dump
fd.close()
#----------- Input Output
def do_printing():
str_var = "very long"
int_var = 50
print("This is a " + str_var + " string!\n")
print("To print this integer " + str(int_var) + "\n")
print ("The length of \"" + str_var + "\" is " + str(len(str_var)) + " characters.")
print ("The length of \"{}\" is {} characters.".format(str_var,len(str_var)))
print ("The length of \"{1}\" is {0} characters.".format(str_var, len(str_var)))
#https://docs.python.org/3/library/stdtypes.html#str.format
# A string is a string of characters surrounded by " or '
# If you must use a " or ' between the same quote escape it with \
quote = "\"Always remember your unique,"
# A multi-line quote
multi_line_quote = ''' just
like everyone else" '''
print(quote + multi_line_quote)
# To embed a string in output use %s
print("%s %s %s" % ('I like the quote', quote, multi_line_quote))
# FUNCTIONS -------------
# Functions allow you to reuse and write readable code
# Type def (define), function name and parameters it receives
# return is used to return something to the caller of the function
def addNumbers(fNum, sNum):
sumNum = fNum + sNum
return sumNum
print(addNumbers(1, 4))
# Can't get the value of rNum because it was created in a function
# It is said to be out of scope
# print(sumNum)
# If you define a variable outside of the function it works every place
newNum = 0;
def subNumbers(fNum, sNum):
newNum = fNum - sNum
return newNum
print(subNumbers(1, 4))
# USER INPUT -------------
print('What is your name?')
# Stores everything typed up until ENTER
name = sys.stdin.readline()
print('Hello', name)
# STRINGS -------------
# A string is a series of characters surrounded by ' or "
long_string = "I'll catch you if you fall - The Floor"
# Retrieve the first 4 characters
print(long_string[0:4])
# Get the last 5 characters
print(long_string[-5:])
# Everything up to the last 5 characters
print(long_string[:-5])
# Concatenate part of a string to another
print(long_string[:4] + " be there")
# String formatting
print("%c is my %s letter and my number %d number is %.5f" % ('X', 'favorite', 1, .14))
# Capitalizes the first letter
print(long_string.capitalize())
# Returns the index of the start of the string
# case sensitive
print(long_string.find("Floor"))
# Returns true if all characters are letters ' isn't a letter
print(long_string.isalpha())
# Returns true if all characters are numbers
print(long_string.isalnum())
# Returns the string length
print(len(long_string))
# Replace the first word with the second (Add a number to replace more)
print(long_string.replace("Floor", "Ground"))
# Remove white space from front and end
print(long_string.strip())
# Split a string into a list based on the delimiter you provide
quote_list = long_string.split(" ")
print(quote_list)
# convert string number to integer
print int('0xA', 0) + 2
def get_input():
num1 = input("Give me a number")
num2 = input("Get me another number")
print ("Sum of the numbers is " + str(num1+num2))
# You can print a string multiple times with *
print('\n' * 5)
#--------------------------- Python Build-in Functions
def constructor_form():
y = dict(x=1)
def literal_form():
x = {'x' : 1}
def disassm_build_in():
c = "cat"
constructor_form()
literal_form()
'''
#done at cmd line to disassemble functions into python bytecodes
import dis
dis.dis(constructor_form())
dis.dis(literal_form())
#used to time execution of small code snippets
import timeit
timeit.timeit("{'x': 1}", number=10000000)
timeit.timeit("dict(x=1)", number=10000000)
'''
def do_maths():
int_var = 4
float_var = 1.89
round_var = round(float_var)
print round_var
print type(round_var)
print type(int(round_var))
print (sqrt(int_var))
#Use of lambda the anon func,dict and get()
def dispatch_dict(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()#Because Python func are first class they can be return values
#To use:
#print dispatch_dict('add',3,4)
#--------------------------- OOP Classes
def use_class():
class Student:
def __init__(self, name, major, gpa, is_lazy):
self.name = name
self.major = major
self.gpa = gpa
self.is_lazy = is_lazy
#function inside a class
def on_honor_roll(self):
if self.gpa >= 3.5:
return True
else:
return False
stud1 = Student("John", "science", 3.4, True)
stud2 = Student("Pete", "maths", 1.5, False)
print('Student: {} is on honor roll ? {}'.format(stud1.name,stud1.on_honor_roll()))
# CLASSES AND OBJECTS -------------
# The concept of OOP allows us to model real world things using code
# Every object has attributes (color, height, weight) which are object variables
# Every object has abilities (walk, talk, eat) which are object functions
class Animal:
# None signifies the lack of a value
# You can make a variable private by starting it with __
__name = None
__height = None
__weight = None
__sound = None
# The constructor is called to set up or initialize an object
# self allows an object to refer to itself inside of the class
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def set_height(self, height):
self.__height = height
def set_weight(self, height):
self.__height = height
def set_sound(self, sound):
self.__sound = sound
def get_name(self):
return self.__name
def get_height(self):
return str(self.__height)
def get_weight(self):
return str(self.__weight)
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name, self.__height, self.__weight,
self.__sound)
# How to create a Animal object
cat = Animal('Whiskers', 33, 10, 'Meow')
print(cat.toString())
# You can't access this value directly because it is private
# print(cat.__name)
# INHERITANCE -------------
# You can inherit all of the variables and methods from another class
class Dog(Animal):
__owner = None
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
self.__animal_type = None
# How to call the super class constructor
super(Dog, self).__init__(name, height, weight, sound)
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
print ("Dog")
# We can overwrite functions in the super class
def toString(self):
return "{} is {} cm tall and {} kilograms and says {}. His owner is {}".format(self.get_name(),
self.get_height(),
self.get_weight(),
self.get_sound(),
self.__owner)
# You don't have to require attributes to be sent
# This allows for method overloading
def multiple_sounds(self, how_many=None):
if how_many is None:
print(self.get_sound)
else:
print(self.get_sound() * how_many)
spot = Dog("Spot", 53, 27, "Ruff", "Derek")
print(spot.toString())
# Polymorphism allows use to refer to objects as their super class
# and the correct functions are called automatically
class AnimalTesting:
def get_type(self, animal):
animal.get_type()
test_animals = AnimalTesting()
test_animals.get_type(cat)
test_animals.get_type(spot)
spot.multiple_sounds(4)
#from Chef import Chef #used if class Chef is in another file Chef.py
def use_inheritance_class():
class Chef:
def make_chicken(self):
print('The Chef make chicken.')
def make_salad(self):
print('The Chef make salad.')
def make_special_dish(self):
print('The Chef make bbq ribs.')
class ChineseChef(Chef):
#the other functions is inherited from Chef class
#function is overwritten
def make_special_dish(self):
print("Make steam fish")
def make_noodles(self):
print('The chef make noodles')
West_Chef = ChineseChef().make_chicken()
East_Chef = ChineseChef().make_special_dish()
'''
do_printing()
print "Done\n\n"
#do_maths()
print "Done\n\n"
#get_input()
print "Done\n\n"
#use_lists()
print "Done\n\n"
#use_tuples()
print "Done\n\n"
#use_if_else()
print "Done\n\n"
use_dictionary()
print "Done\n\n"
#use_loops()
print "Done\n\n"
#do_catch_error()
print "Done\n\n"
use_files()
print "Done\n\n"
use_hex_bytes()
disassm_build_in()
print "Done\n\n"
use_class()
use_inheritance_class()
print "Done\n\n"
'''
do_rotation()
print "Done\n\n"
print "Done\n\n"
print "Done\n\n"
#Troubleshoot/Debugging commands
'''
type()
https://docs.python.org/3/library/functions.html#type
dir()
https://docs.python.org/2/library/functions.html#dir
repr()
https://docs.python.org/2/library/repr.html
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment