Skip to content

Instantly share code, notes, and snippets.

@mjgpy3
Created August 10, 2016 01:45
Show Gist options
  • Save mjgpy3/addb2bdf1ba118142b947bc0b54afde5 to your computer and use it in GitHub Desktop.
Save mjgpy3/addb2bdf1ba118142b947bc0b54afde5 to your computer and use it in GitHub Desktop.
Some Python Basics
print "hello world"
""" This is a multi-line comment... no it's not
int main() {
return 0;
}
"""
def main():
return 0
# Weakly typed
a = 42
a = "hello"
day = 'tuesday'
if day == 'friday':
print "I'm in love!"
elif day == 'tuesday':
print "not as fun"
i = 0
while i < 50:
#print "hi"
i += 1
names = ['John', 'Abbey', 'James', 'Danny']
"""
for (int i = 0; i < ITEMS_SIZE; i += 1) {
type name = names[i];
}
"""
for name in names:
print "hello " + name
print names
print names[2]
try:
names[90]
except Exception as e:
print e
my_hash_table = {}
my_hash_table['name'] = 'John'
my_hash_table['favorite_drink'] = 'scotch'
my_hash_table[42] = 'the answer'
print my_hash_table
print my_hash_table['favorite_drink']
pair = ('John', 'scotch')
triple = ('John', 'scotch', 20)
print pair[0]
my_hash_table[pair] = 'hi there'
print my_hash_table
print my_hash_table[pair]
print 12 + 99
print 'a' + 'b'
numbers = [1, 2, 3] + [4, 5, 6]
# LOOK AT NUMPY http://www.numpy.org/
print numbers[3:]
print numbers[-1]
print numbers[-2]
print numbers[1:-1]
print numbers[::-1]
# List comprehensions!!!!
# [<what's being returned> <how you're looping> <?conditional?>]
evens_tripled = [i*3 for i in numbers if i % 2 == 0]
print evens_tripled
# checking containment
print 42 in evens_tripled
print 18 in evens_tripled
# Strings are OBJECTS
# OBJECTS have methods
# Methods are functions that are attached to objects
print ', '.join(names)
# In Python sometimes
# - It's hard to guess what's gonna be a function vs. a method
# - If it's a method, it's hard to guess what it's on
names_containing_J = [name for name in names if 'J' in name]
# `and` and `or` not && and ||
print names_containing_J
# TODO: Visit polymorphism
class Person:
# Constructor
def __init__(self, name):
self.name = name
def greet(self):
print "Hello " + self.name
john = Person('John')
john.greet()
print john.name
# Polymorphism through "duck-typing"
class Dog:
def greet(self):
print "Woof"
fido = Dog()
for greetable in [john, fido]:
greetable.greet()
with open('./hello.py', 'r') as f:
text = f.read()
print text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment