Strings
# declare variable string
someString = "Hoy Matey"

# Yank positional 1 to 3 within string
yank = someString[1:3] #yank="Hoy"

# Strip leading/trailing white spaces
stripWhiteSpaces = someString.strip() #stripWhiteSpaces="Hoy Matey"

# Convert to uppercase or lower
upperCaseString = someString.upper() #upperCaseString="HOY MATEY"
lowerCaseString = someString.lower() #lowerCaseString="hoy matey"

# Substitution
jToHString = someString.Upper().replace("J","H")
Operators
Arithmetic Operators:
-----------
* :multiply
** :exponential
/ :division
// :floor division
+ :plus
- :minus
% :modulus (returns remainder)

Comparison Operators:
-----------
in :inclusive
not in :reverse inclusive
= :equal
!= :not equal
or :disjunction (case sensitive)
and :conjunction
is :returns true or false
isnot :negative version of is

Bitwise Operators:
-----------
& :AND
| :OR (note that this is not a pipe command)
^ :XOR
~ :NOT
<< :shift left
>> :shift right
Lists

In Python, List is an implementation of Array. An list is a fixed size, ordered, mutable collection. They are very efficient to create, but must always be a single type. List manages its elements as a doubly linked list and does not provide random access.

# Declaration
cities = ["Anaheim","Long Beach","Laguna Niguel"]

# Select index
firstCity = cities[0]

# Append to tail of array
cities.append("Huntington Beach") # cities = ["Anaheim","Long Beach","Laguna Niguel","Huntington Beach"]

# Pop the first element or array
cities.pop()

# Remove value at specific index
cities.pop([index])

# Insert item into position 3 within array
cities.insert(2,"Orange") #cities = ["Anaheim","Long Beach","Orange","Laguna Niguel","Huntington Beach"]

# Remove specific match of city named "Orange"
cities.remove("Orange")

# return the length of array/list
len(cities)

# Count the number of occurences
cities.count("Anaheim")

# Order the list and reverse
cities.sort().reverse()

# Clean the list
cities.clear()
Deque

Deque manages its elements with a dynamic array, provides random access, and has almost the same interface as a vector. It can be thought of as an advanced Vector type that supports constant time insertion and removal of elements of the first and last positions – more efficient than list’s methods. Does not have some of list’s methods such as splice(), etc.

# import deque data type
from collections import deque

# import list into deque data type
queue = deque(cities)

# remove first item
queue.popleft()

# remove last item
queue.popright()
Tuples

A tuple is a grouping of unnamed, ordered values. Its allowance of multiple types of values is an incompatiblity to arrays and lists.

# declare variable of mixed types: int, string, and float
someTuple = (1,"car",3.14)

# return the length of tuple
len(someTuple())
Sets

Similar to Lists with the major difference in that sets, unlike lists or tuples, cannot have multiple occurrences of the same element and store unordered values. Due to this characteristic, sets are highly useful to efficiently remove duplicate values from lists or tuples.

# Append a List into a Set
cities = {"Anaheim","Long Beach","Laguna Niguel"}
more_cities = ["orange", "Los Angeles", "Mahattan Beach"]
cities.update(more_cities)

# Remove an item in a set
cities.remove("orange")
cities.discard("orange")

Dictionaries

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values much similar to JavaScript’s.

# Create dictionary
myDictionary ={
"cover": "Paperback"
"pages": 1754
"version": "1.24"
}
# Get the number of pages
myDictionary.get("pages")
# Change value of an element
myDictionary["version"] = "1.25"
# Add new element
myDictionary["newElement"] = "something"
# Remove element from Dictionary
myDictionary.pop("newElement")
# Remove all values inside dictionary
myDictionary.clear()
Conditionals

As a C-based interpreted language, if..then..else condition statements work the same way with a simplier syntax as:

if x {operator} y {and|or} a {operator} b: #colon is required
statements to execute…
elif x {operator} y:
statements to execute…
else:
statements to execute…

Conditional is effective at stopping a while loop. For example:

if variable operator value:
break|continue
# break will exit the loop
# continue is to skip this iteration

WHILE Loops Syntax:

while variable operator value:
statements to execute...

For Loops Syntax:

for variable {in|range(int)} Array|Tuple|Dictionary:
statements to execute...
Functions:
# define a function
def someFunction():
statements to execute
# call a function
someFunction()
# working with parameters
def addNumbers(x,y):
return x+y
# set parameter with a default value
def checkAge(age=18):
"your age is " + age
# working with lambda (anonymous function that can only have 1 expression)
variable = lambda arguments : expression
addNumbers = lambda x,y : x+y
addNumbers(5,3)
# Recursive function to print lines starting with number to 100
def printLines (lineNumber):
if (lineNumber>0 or lineNumber<=100):
print(printLines(lineNumber+1))
else:
break
Class

Class is an object constructor. Inheritance is possible due to the availability of classes. Python uses different keywords as pointers to a class’ properties.


Following is an illustration of constructing a object with the special built-in __init__() function, which will be called the moment the class is instantiated. Notice the parameter ‘this’ being used by Python is similar to JavaScript’s ‘this’ keyword. It is a reference to the current instance of the class to access variables that belong to that instantiated object. Python doesn’t require the exact name of ‘this’ keyword – it could be any label. The behavior will comply as long as it’s the first parameter of a function inside the class.

class Vehicle:
def __init__(this,make,model,year):
this.make=name
this.model=model
this.year=year

myVehicle = Vehicle("Toyota","Prius",2014)
Inheritance

I’ve intentionally created the Vehicle class above with the design of a parent type. Hence the below examples will follow that previous illustration.

# Create a new class named Car that inherits from the Vehicle class without adding anything extra. Notice the ‘pass’ keyword

class Car(Vehicle):
pass

# Once the __init__() function of a child class is defined, that new class will loose inheritance of the parent’s original __init__() function. To work around this behavior, it is necessary to declare the new __init__() function with a call to the parent’s __init__() to import all of that function’s fields (to be get/set using public properties aka functions). Afterward, it will then possible to load additional parameters into the new class

class Car(Vehicle):
def __init__(this,color,origin):
Vehicle.__init__(this,make,model,year)
this.color=color
this.origin=origin

myCar = Car("Toyota","Prius",2014,"grey","Japanese")

# Adding new methods

class Car(Vehicle):
def __init__(this,color,origin):
Vehicle.__init__(this,make,model,year)
this.color=color
this.origin=origin
def drive(this):
print("I'm driving a ", this.orgin, this.year, this.color, this.make, this.model)
Iterators

Iterate is a verb with the meaning to repeat. In Python, it is an object named iter(). This object can take other objects such as list, deque, tuple, dictionaries, sets, etc. as arguments to be processed. There is a native function called __next__() to do what the name implies.

# Simple iteration of a string

someString="Calculus"
iterateString=iter(someString)
print(next(iterateString)) #output: C
print(next(iterateString)) #output: a

# create a class named Counting with two functions to initialize and iterate values initialized as 1 using next() function. The break condition is set at 100.

class CountTo100:
def __init__(this):
this.value=1
return this #upon instantiation, 'this' object is returned
def __next__(this):
if this.value<=100:
placeholder=this.value #at first call of 'next', the init 'this' was made available. Hence, this.value became accessible to be assigned to a variable herein labeled placeholder
this.value+=1 #increments by 1
return placeholder
else:
raise StopIteration #this is an important keyword equivalent to break

# Usage: assign class iter() to youCount with class CountTo100() as its argument

youCount=iter(CountTo100())

for number in youCount:
print(number)
Modules

Consider these as synonymous with libraries. These are usually external files that contain a set of functions to be included in the current program. Python file extension is ‘*.py’ – easy enough.

Example: anaheimlibrary.py

# Create a class (object) inside anaheimlibrary.py
book1 = {
"title": "Python for Dummies"
"Author":"Some Dude"
}

How to include external libraries into your program?

# notice that the import statement doesn't require file name extension as the .py is implicitly assumed by Python

import anaheimlibrary as mylibrary #creating alias is optional

# use the dot notation to access class member of a library
myBookTitle = mylibrary.book1["title"]

How to list all the classes and functions inside a library?

import anaheimlibrary
dir(anaheimlibrary) #output: book1

How to limit the import toward just 1 class inside a library?

from anaheimlibrary import book1
Try and Catch in Python

As available to other C-based languages, this useful method is available in Python as well. The syntax includes four components: try, except, else, and finally.

try:
print(undefinedVariable)
except NameError:
print("variable ",undefinedVariable," is not defined")
except: #catch other exceptions
print("some other error has occured.")
else:
print("no errors.")
Interacting with Files
def overwriteIndex:
try:
file = open("/var/www/html/index.html")
file.write("you\'ve been hacked")
except:
print("Good! index.html shouldn't be writable.")
finally:
file.close