Skip to content

Instantly share code, notes, and snippets.

@twilson90
Last active October 22, 2018 12:40
Show Gist options
  • Save twilson90/ee4b6de1ba51c6217fd849a0045f541e to your computer and use it in GitHub Desktop.
Save twilson90/ee4b6de1ba51c6217fd849a0045f541e to your computer and use it in GitHub Desktop.
# I'm sure you already know about basic data types, like ints, floats, strings and bools, so let's start with loops and basic data structures.
# Let's see all the ways we might generate a sequence of numbers from 0-9.
# First, using a while loop and a list:
zero_to_nine = []
i = 0
while i < 10:
zero_to_nine.append(i)
i += 1
# Using a for loop, a list and an iterative:
zero_to_nine = []
for i in range(10):
zero_to_nine.append(i)
# Using python's list comprehension and an iterative:
zero_to_nine = [i for i in range(10)]
# Converting an iterative to a list:
zero_to_nine = list(range(10))
# You might be wondering what an iterative is.
# range(10) returns an iterative object, a for loop will grab the next value with each iteration, and the iterative will continue. But the iterative is not a list containing every value all at once.
# It might be better to call it a generator, because each value is generated on the spot each time the for loop moves wants the next value.
# So if you want to count to a million with a for loop, printing each result as you go along, you wouldn't create a list containing each number before looping it, that would use more memory than necessary (storing each value when they are only needed individually) and there would be a noticeable wait time to generate the list before you could start traversing it in a loop. Also it allows you to break out of the loop before generating all the numbers in the sequence.
# Iteratives are very useful in this respect, but for generating small collections of numbers this all a bit trivial.
# a list is pretty self-explanatory. It's a list of values. You can access those values like so:
print(zero_to_nine[5]) # output: 4
print(zero_to_nine[7]) # output: 6
# You can also amend the list in various ways.
# Read more: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
# Similar to a list is a tuple, which is basically a fixed-length list. You cannot append or remove from a tuple:
zero_to_nine = tuple(zero_to_nine)
# or
zero_to_nine = (0,1,2,3,4,5,6,7,8,9)
# In C, tuples are referred to as arrays, but in other languages, arrays are often more like Python's lists. It's all rather confusing.
# There are similar structures for keeping a collection of values, like sets, which have no defined order and do not do not allow repeat values:
zero_to_nine = set(zero_to_nine)
# or
zero_to_nine = {0,1,2,3,4,5,6,7,8,9}
print(len(zero_to_nine)) # outputs: 10
# Imagine a set like a circle in a venn diagram containing lots of values in no particular order.
# Sets can be very useful, you can easily find subsets, intersections, remove one set from another or add them together.
# If I try to add values that already exist...
zero_to_nine.add(7)
zero_to_nine.add(9)
# the set remains the same length, with the same contents, because they already existed in the set:
print(len(zero_to_nine)) # outputs: 10
# Read more: https://docs.python.org/3/tutorial/datastructures.html#sets
# And finally, dictionaries (often referred to as maps), also have no defined order:
zero_to_nine = {"zero": 0, "one":1, "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9}
print(zero_to_nine["five"]) # outputs: 5
# unlike the previous 2 examples, dictionaries have 2 values associated for each item, a key and a value.
# there are several ways to iterate a dictionary:
for key in zero_to_nine():
print(key)
for value in zero_to_nine.values():
print(value)
for key, value in zero_to_nine.items():
print(key, value)
# The key doesn't have to be string, they can be any data type.
# Read more: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
#--------------------------------------------------------------------------------------
# You can also define functions with the def keyword, which are vital for repetetive tasks and keeping your code structured.
# You can define many parameters, or none at all:
def sequence_of_ten():
return [0,1,2,3,4,5,6,7,8,9]
def sequence_of_ten_from(n):
return [n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8,n+9]
zero_to_nine = sequence_of_ten()
ten_to_nineteen = sequence_of_ten_from(10)
# Finally, there are classes.
# A class defines an instance. With these you can then create multiple instances with defined characteristics.
# Lists, Dictionaries, Sets, at the end of the day, they're just fundemantal class definitions.
# You can define your own using the class keyword:
all_people = [] # this is a variable that will not be instanced.
class Person:
def __init__(self, name):
all_people.append(self) # keep track of all people.
self.name = name # this stores the name in the instance itself, otherwise it's forgotten.
print("I am a person, my name is %s" % name)
def walk(self, destination):
...
def breathe(self, bpm=18.0):
...
def die(self):
all_people.remove(self)
lars = Person("Lars") # this creates a new person
print(lars.name) # outputs: "Lars"
tom = Person("Tom")
print(tom.name) # outputs: "Tom"
print(lars in all_people and tom in all_people) # outputs: True
print(lars == tom) # outputs: False
# You may want to inherit these traits to create a more specialized version of a person:
class Lars(Person):
super(Person, self).__init__("Lars") # this calls the Person.__init__
def play_guitar():
...
def compete_in_maths_competition():
...
lars = new Lars()
lars.compete_in_maths_competition()
# but eventually the day will come, as it will for all of us...
lars.die()
print(lars in all_people) # Outputs: False
lars = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment