Skip to content

Instantly share code, notes, and snippets.

@maxvonhippel
Last active April 30, 2020 21:47
Show Gist options
  • Save maxvonhippel/42367d956d58db48baba5b61f9526360 to your computer and use it in GitHub Desktop.
Save maxvonhippel/42367d956d58db48baba5b61f9526360 to your computer and use it in GitHub Desktop.
A brief tutorial on having fun with Python.

This is intended to be a brief tutorial on having fun with Python.

Getting started.

Open the Terminal application on your Mac or Linux computer.
Open Sublime Text.
Type command n to create a new document. Type command s to save this document. When it asks for a path and file name, put it on your desktop, and save it as banana.py. Now, in your new file, write the following:

print("banana banana banana")

Now, in your terminal, type

python ~/Desktop/banana.py

Your terminal should say:

banana banana banana

Now you know how to run Python code! (Not only that but you know the best way to run Python code. Any other way is objectively inferior.)

Next, let's make a class. A class is different from a struct because it can have methods / functions. A struct is what you might refer to as its own type. A real computer scientist would probably have a heart-attack reading this paragraph, but it's correct-enough for now!

Note: If you want to be bored, you can read the correct documentation on classes here.

In banana.py, write the following:

class gnarleyBanana: 
  def __init__(self, name, job):
    self.myName = name
    self.myJob  = job
  
  def what_is_my_job(self):
    print("I am {} and my job is {}".format(self.myName, self.myJob))

sickBanana = gnarleyBanana("Max", "do the groovy dance")
sickBanana.what_is_my_job()

Now if you do the same thing as before, that is,

python ~/Desktop/banana.py

It should print:

I am Max and my job is do the groovy dance

Will this work? I am not sure since I didn't bother to test the code. But if it fails I figure you can probably debug it.

Finally, I will give you an example of how to use this in real life:

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Complex(3.0, -4.5)
print(x.r, x.i)

This should print out:

(3.0, -4.5)

Note that this Complex example is stolen directly from the official docs.

Hope this helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment