Conclusion - Learning to Program with Python 3 (basics)




Hello and welcome to part 15, the last part, of the Python 3 basics tutorials. In this video, we're just going to wrap everything up, and you're all being kicked out!

Understanding the syntax of Python is great and all, and Python by itself is indeed a great language, but the fundamentals of Python aren't why Python is a successful language. There are plenty of fun-to-write languages that are just like Python, such as Ruby, Julia, even R. What makes Python the victor is the community and 3rd-party packages. While we can do a lot with just an installation of Python and the standard library, we can do infinitely more with all of the 3rd party libraries out here.

There are generally two major ways that you will get a 3rd party package. One is the more official route via PyPi, which is the Python Package Index. The other is straight off of github. Most packages will come with a setup.py file that you can use to run and install things. To do that, you just download the github project, then run:

py -3.7 setup.py install. Simple as that. This will install the package for you, then you just need to import it.

Okay, but what really is a package? Let's say you make a program, called examplemod.py:

def do_a_thing():
    print("Hey we did a thing!")

Now, in a completely different script, say, part15.py, we can import this and print it:

import examplemod

examplemod.do_a_thing()

Sure enough, the result is:

Hey we did a thing!
>>> 

Next, we can import a specific thing from an import. For example:

from examplemod import do_a_thing

do_a_thing()

Now we import that exact function. Be careful though, you will want to make sure you don't have anything conflicting function names. For example, main() might be a common function name. You'd want to make sure you didn't have 2, because the one that was called in last will take precedent.

We can import multiple things like the above as well:

Modifying examplemod.py:

def do_a_thing():
    print("Hey we did a thing!")

def do_another_thing():
    print("some other thing!")

Back in part15.py now:

from examplemod import do_a_thing, do_another_thing

do_a_thing()
do_another_thing()
Hey we did a thing!
some other thing!
>>> 

You can also do wildcard imports:

from examplemod import *

do_a_thing()
Hey we did a thing!
>>> 

But this is generally frowned upon, since it's harder to read, like, where the heck did do_a_thing come from? What if you did 3 wildcard imports from different places? It makes things pretty darn hard to figure out, and you run a much higher risk of overlapping function names.

We can also import things as something else to rename it. For example:

from examplemod import do_a_thing as dat

dat()
Hey we did a thing!
>>> 

You can also package packages into folders/directories. If you had a larger library of scripts, this is probably what you'd use. For example, you could do:

from moddir.examplemod import do_a_thing

do_a_thing()

Alright great, so that's really all a module is. In this case, we built one locally, just so we could see it in action. Python searches for packages called whatever you import first locally, then it checks the standard library, then 3rd party packages. This is why, say you're learning a new package, a common mistake is to call your script the same name as you're working with. The problem is... you will just be importing the script you're working in, then hit weird errors. Don't do that!

It's more likely you'll be importing scripts you've installed. While I showed the py -3.7 setup.py install method already, arguably the most common way that you will install a package is actually through pip. Pip stands for Pip installs Packages. Yeah, I know, wooo recursive! Like php. Greeeat.

ANYWAY, we can use pip to install whatever packages we want. For example, I decided to just keep this dirt simple and use colorama here. Also, it gives me a moment to warn you all.

Python is fun and stuff right now, but remember... Python is a fully-fledged programming language. Any code you download from github, the Python Package Index, or anywhere else, can be malicious and would almost certainly go unnoticed by most people's firewalls. It doesn't take much to upload your own package to PyPi for others to install, so you need to pay attention and be careful. Just recently: Twelve malicious Python libraries found and removed from PyPI. It's unlikely that a major package like TensorFlow, or Numpy will have any malicious code, but, as you'll see fromt he above link, it's mostly with packages with typoed names. Normally, if you typo a name, you'll just get an error, but what some people do is actually upload a package with a typoed name, so everything goes through just fine and you never even notice what you've done! So... pay attention. You're downloading code here that you're going to run, treat it as possible explosive that it is and make sure you get what you intended!

Okay, next up, let's grab colorama. To do this, we can just do:

py -3.7 -m pip install colorama

Colorama is a package that lets us add color to our console output. If everyone used Colorama, the world would be a way more interesting place!

Depending on the package you use, documentation may be found in a variety of ways. Lots of packages use readthedocs.org, others have their own dedicated websites, some have it on github, and some, if they're basic enough, just write it on their PyPi page. Colorama has just written their docs on their page.

So let's check it out. I scroll down til I see some code. I see first we need to initialize colorama by doing a from colorama import init

If I feel so inclined, I read that this is really only necessary for windows machines, and does nothing on others. Cool. So I can expect this to work on any machine that runs it. Got it. Then, we can modify the background, foregraound, and then in general the style. Looks like the most important attribute of Style is the ability to just clean up with Style.RESET_ALL. Okay great, let's add this to TicTacToe, and color player 1 and 2 differently:

from colorama import Fore, Back, Style, init

init()

Now, we just need to modify the display of game rows. For example, inside our game_board function, as we enumerate over the game_map to print the rows, instead we can do:

        for count, row in enumerate(game_map):
            colored_row = ""
            for item in row:
                if item == 0:
                    colored_row += "   "
                elif item == 1:
                    colored_row += Fore.GREEN + " X " + Style.RESET_ALL
                elif item  == 2:
                    colored_row += Fore.MAGENTA + " O " + Style.RESET_ALL
            print(count, colored_row)

And now, as we play, we get some beautiful coloring, like:

python tutorials

Awesome! We could fix other elements, like coloring which player is currently playing, adding some spaces around the game board maybe to make it easier to read...etc, but I think you get the idea. Okay, that's packages.

If you're using an editor that has plugins, I suggest looking into a PEP 8 linter to get you in the habit of writing with PEP 8 styling. The only rule I think worthy of breaking is the silly 78-character limit. I think maybe 120 or something is too long, but 78 is not yet too long. If you use something like a PEP 8 linter plugin, it'll just hint at you that you've made some mistakes. For example, I will show how to get one with Sublime-Text, but you can probably find one for other editors pretty easily, and, remember, who cares what editor you use. Poke around and use one that you like!

With Sublime-Text:

  1. Head to tools in the menu bar, choose "install package manager"
  2. Then hit ctrl+shift+p
  3. Here, you type a package name and you install it. I use SublimeLinter-flake8
  4. To use this linter, we also need the flake8 package for python, so do a py -3.7 -m pip install flake8
  5. Now you have PEP 8 linting!

Okay last things. Open a fresh Python script, or run python in the terminal. Do:

import antigravity

:)

There's also a nice import for braces. It's under __future__, which is where all the things being back-ported go. You can ...try... to import braces this way:

from __future__ import braces

That's it, now get out of here and make something fun. If you're having trouble deciding what, look around the pythonprogramming.net home page and click on some topics that interest you. Think about why you wanted to learn to program in the first place. What did you envision you would do if you learned to program? Do that. Don't be dissuaded by complexity. The first project I worked on was sentiment analysis and natural language processing, which most people would have told me would be a horrible starting project, but that's what I was interested in doing, and I learned a ton along the way. You can also check out the Python subreddit to see the recent happenings with Python and maybe see something you'd like to poke around with there. Come join our Discord to hangout, get help, or ideas on what next.

I will leave you with one final import, which gives you the Zen of Python:

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

The next tutorial:





  • Introduction to Python 3 (basics) - Learning to Program with Python 3
  • Tuples, Strings, Loops - Learning to Program with Python 3 (basics)
  • Lists and Tic Tac Toe Game - Learning to Program with Python 3 (basics)
  • Built-in Functions - Learning to Program with Python 3 (basics)
  • Indexes and Slices - Learning to Program with Python 3 (basics)
  • Functions - Learning to Program with Python 3 (basics)
  • Function Parameters and Typing - Learning to Program with Python 3 (basics)
  • Mutability Revisited - Learning to Program with Python 3 (basics)
  • Error Handling - Learning to Program with Python 3 (basics)
  • Calculating Horizontal Winner (tic tac toe) - Learning to Program with Python 3 (basics)
  • Vertical Winners - Learning to Program with Python 3 (basics)
  • Diagonal Winners - Learning to Program with Python 3 (basics)
  • Bringing Things Together - Learning to Program with Python 3 (basics)
  • Wrapping up Tic Tac Toe - Learning to Program with Python 3 (basics)
  • Conclusion - Learning to Program with Python 3 (basics)