The truth about Boolean values in Python

Introduction

George Boole was an English mathematician who is credited with having invented a branch of algebra in which an expression is evaluated to one of the truth values, true or false. Unsurprisingly, this became known as Boolean algebra (I’m hoping that Thompsonian snark will be a thing in the not too distant future).

This post looks at how all objects in Python can be tested for a truth value and what that means.

True dat

In Python, you can assign True or False to any variable.

That’s all well and good and is very useful if we want to have a binary type value to assign, rather than trying to use 0’s and 1’s,  ‘yes’ or ‘no’ etc., which could cause confusion with your code where you also use those values for other purposes e.g. it probably doesn’t make sense to have 5 -5 = False.

You can’t handle the truth

Additionally, in Python, any object can be tested to see if it is truthy or falsy. What does that actually mean? Take a look at the following code:

 

A nice and simple example but for beginners to Python, the second if statement might cause confusion. Initially, let’s confirm we understand the first if statement; if the foo variable refers to the value 5, that branch runs i.e. bar() is called, if not, that branch is skipped.

What about the second example. What is if foo: doing? This is where Python tests the truthiness or falseness of the foo variable. In short, that statement means if foo is truthy, run that branch, if it is falsy, skip that branch. So bar() will only be called if foo is truthy.

True or False

The truth will set you free

So what determines if something in Python is truthy or falsy? It depends on the type being evaluated. The table below lists the main types within Python. Remember that these are all objects in Python.  (Some other languages consider data types such as strings and tuples to be primitives.)

Type When is it truthy? When is it falsy?
str Not empty Empty, ”
list Not empty Empty, []
tuple Not empty Empty, ()
set Not empty Empty, set()
dict Not empty Empty, {}
int Not zero, 0 Zero, 0
float Not 0.0 0.0
bool True False
NoneType Never Always
Function Always Never
Class Always Never

Let’s go back to that second if statement.

There is a really handy built-in function we can use to tell us if something is truthy or falsy, the bool() function.

Summary

This post began discussing the True and False Boolean values you can assign in Python and then went on to discuss how all objects in Python can be tested for a truth value and what that means. I hope this has been useful.

Till the next time.

Getting started with coding – Part 7 – Next Steps

Introduction

In part 6, we looked at a number of training options to help take your knowledge and skills to another level.

In this final part of my Getting Started With Coding series, we will review what we’ve covered so far and then try to answer the question that will, at some point, inevitably crop up. “What do I do next?”. Continue reading “Getting started with coding – Part 7 – Next Steps”

Getting started with coding – Part 5 – Version control

Introduction

In part 4, we discussed some additional tools to help your coding. In part 5, we look at version control, which is a way of tracking changes you make to your code (or in a wider sense, documents, information, etc.). As it is such an important topic, I think it warranted its own post, even though technically it is just another tool in your kit. Continue reading “Getting started with coding – Part 5 – Version control”

Getting started with coding – Part 3 – Editors

Introduction

So you want to start following examples you’ve found online or in a book to learn more about your chosen language from part 2. Which editors should you consider to start knocking up some super useful scripts? Part 3 looks at three broad categories, giving some suggestions along the way. Continue reading “Getting started with coding – Part 3 – Editors”

Getting started with coding – Part 2 – Languages

Introduction

In part 1 of this series, we addressed the key concerns people starting to code might have and also set out some key reasons why you should give it a go in spite of those, often unfounded, concerns. In part 2, we cover off how to go about picking one of the languages to learn to code in from the numerous choices. Continue reading “Getting started with coding – Part 2 – Languages”

Taking the Python Challenge

Introduction

A few months back, I came across a cracking website called Python Challenge, which poses a number of increasingly difficult challenges.

Crazy and fun at the same time

This isn’t a site for complete beginners. It assumes you already know the basics of things like loops, branching logic, various data types, etc. It also assumes you have a specially wired brain so don’t be surprised if you run in to a few brick walls where you will probably have to cheat a little i.e. find a solution on line.

However, the best thing about this site is that each of the 33 challenges (current as of 28/10/16) covers a different skill set and gets you using different Python modules in creative ways e.g.

  • re for regular expressions
  • pickle for (de)serialising Python objects
  • zipfile for working, unsurprisingly, with zip files

I found this approach really useful in forcing me to learn new tools to solve a problem, probably one of the best ways to get familiar with tools that you may need from time to time but don’t want to just plough through some documentation when you need it.

Summary

At some point in your path to learning to code, you’ll probably find yourself stumped as to what to do next. You’ve learnt the basics, you’ve applied them to some problems you’ve had but you aren’t sure how to widen your horizons.

Try out Python Challenge and see how many challenges you can get through before your head explodes.

Till the next time.

Introduction to Python

Introduction

Over the course of my IT career, I have used a few different platforms to create tools that help me in my day to day work. Initially, VBScript used to be my scripting tool of choice when I was a Sysadmin. When PowerShell was released, I quickly embraced it and really liked it’s human readable verb-noun structure. It saved my bacon on many an Exchange deployment/migration. I’ve also dabbled in various flavours of Visual Basic over the years to create some small applications but I am no developer, by any stretch of the imagination.

Over the last 18 months or so, I’ve been looking to learn a tool that was more cross platform, easy to pick up and could be used across the board for not only my networking tasks, but anywhere I could save time and do things more consistently. I probably spent far too long dwelling on the options but about this time last year settled on Python.

This discussion is about Python but that assumes that you have chosen Python yourself as a language you wish to learn. If that isn’t yet the case, the discussion below on which version of Python to use could also be applied to which language you should settle on and the sections further below apply to any programming language you finally set out to learn.

Version

Don’t get hung up on whether to use Python 2 or 3 (or Java, Go, Ruby, C, etc. for that matter). Whilst 2.x fans will argue it has a larger support base including more modules and libraries, more deployed code etc. it is well known that 2.7 was the last version that will be released on that track and the creator of Python, Guido Van Rossum seems to be committed to the 3.x train. I have been learning 3.x because I found that everything I set out to do in my first months learning Python had suitable modules available.

The key is not to spend too much time on this decision though. Take a look at them both, read up on some of the arguments in favour of each and then pick one and stick to it. Most modern Linux distros seem to have both versions installed so if you are really unable to flip a coin, learn both…but learn at least one of them!

As a quick note on why I chose Python over other options I would have to say:

  1. It’s relatively easy to learn
  2. There are loads of on-line resources
  3. It is well supported across many different areas and vendors
  4. I can use it to create the most basic of scripts up to the most elegant of object oriented applications and everything in between
  5. It’s fun!

Tool kit

When I say tool kit, I’m talking about setting up your environment to make working with Python and the code you create more enjoyable. There is nothing worse than trying to learn something new and having to jump through a load of hoops before you get to the good stuff. Take GNS3 back in the early days. I can remember spending up to an hour on some occasions just to get my lab up without crashing. Not fun. The bullet points below briefly cover off the main points you should be getting in place:

  • Platform. I come from a Microsoft background and initially started playing with Python on Windows. I quickly realised that Linux was the way to go. Not only is it better supported and comes already installed on many popular distros, it has the added benefit of upping my Nix skills at the same time. Hoorah!
  • Editor. For me, there are two options here. Either Notepad++ or a Python specific Integrated Development Environment (IDE) and I use both of them depending on my needs. Notepad++ has syntax decoders built in for most languages in use and if you save your file with a .py extension, it will get recognised as a Python file, with nice colour coding to highlight your syntax. An IDE adds better file management and will also have intelligent help systems that can give you pointers on the usage of certain features and syntax. I use Jetbrains Pycharm as an IDE, but most of my scripting is done in Notepad++ at the moment. Make sure you set both of these up in a way that suits your workflow. As an example, I have got my Notepad++ configured to insert four spaces when I press the TAB key as it’s easier to do but Python convention dictates that indents are spaces and not tabs
  • Code repository. You will quickly find that keeping track of your different scripts and the various versions of each of those becomes a time consuming task so you will want to utilise something like Git, which is what GitHub uses. You can get an account for free but just be aware that if you want to keep any of your code private (e.g. it contains database connection strings, or IP address information), then you will need to pay for a private account, which isn’t extortionate. Another option if you are feeling daring is to install your own version of Git

Training materials

The best resources are to be found on-line and there are countless websites that have great content relating to Python on them, with the Python homepage being a great starting place. I haven’t found any really good video based training to date that would pass as a course as such but there are lots of books available on the subject. My favourites so far have been:

  • Python Cookbook (latest edition for Python 3)
  • Hacking Secret Ciphers with Python
  • Python 3 Object Oriented Programming

Read the reviews, use Amazon’s ‘Look Inside’ feature to see if the style suits and start building a reference library to consolidate that knowledge.

Get yourself a project and play, play, play

All those tools and all that knowledge will still make your journey a tedious one if you don’t apply it to the real world. Find a project that could use your Python skills and put them to the test. I initially struggled trying to learn Python from a network engineer perspective as it involved ugly screen scraping techniques on kit without APIs. What I found really useful was when we started using a dashboard application in house that is built on Ruby and converted all the Ruby scripts to Python. I now feel much more confident about tackling  more difficult tasks. The key is not just to type up the scripts you find on-line or in a book but to create something that you needed anyway. This will be so much more rewarding for you in the short term, which will motivate you further in the long term. If you are struggling to find a project, buy a Raspberry Pi and a related project book to get your teeth in to.

Summary

Regardless of what field you work in, if you use a computer on a regular basis and have a number of tasks you repeat, I strongly suggest you look at Python as a great tool to help you get those tasks done quickly and more consistently. You’ll soon start seeing that you can use these skills all over to help make life easier.

[sourcecode language=”python”]
print("Till the next time")
[/sourcecode]

The year of automation, 2015

Introduction

2014 was a slightly strange year for me in some respects. I moved in to a new leadership role, delivered some big projects successfully with the help of my team and got lots of the smaller jobs off my plate, but it still felt like I could have achieved a lot more. The good news is that I’ve been tracking everything that needs addressing so have a good idea of what my team’s priorities are for the coming year already.

My own priorities

My aim is to make 2015 the year of automation. Not in any one area anywhere I think I will hit my two key goals, those being to get a ROI on my time and to standardise as much as possible and I will be using those goals to measure where to focus my efforts. I am already familiar with PowerShell from my SysAdmin days and have built a number of tools in Visual Basic over the years but will be taking what I have learnt about Python over the last few months to a new level. I have already started taking related scripts and creating my own modules and already have ideas on how I want start making bigger applications that are more object oriented.

I also plan on blogging more about my automation journey so expect some Python posts in particular.

Summary

2014 was the year of steadying the ship, ensuring nothing critical fell through the cracks and hopefully helping my team develop personally. I’ve heard people across the industry quote how 2015 will be the year of SDN, IPv6, NFV, blah, blah, blah. I make no such claims, although out of those, I would put my money on NFV and maybe blah. For me though, this year will be about brushing down some old and not recently used skills and giving them a high polish. I won’t need to become a fully blown developer but the skills I intend on picking up will be useful in many areas of my life, both at work and otherwise.

Till the next time.

PyCharm Educational Edition

Introduction

PyCharm is a Python IDE created by Jetbrains. When I decided to go beyond Notepad++ for my Python scripting, I used the free Community Edition of PyCharm to help me with the structuring of my projects. There is also a Professional Edition which essentially adds web development frameworks such as Django and Flask to the mix, but these are currently beyond my requirements

PyCharm Educational Edition

A recent announcement brought the good news that a new Educational Edition was being released. This is basically the Community Edition, but with built in training that uses the IDE features to build up your knowledge. The screenshot below gives an idea of how this works (click it to make it bigger in  new window). The top left window shows the different lessons and tasks within, which come in the form of real Python scripts. Above the script editing window on the right is a brief and to the point explanation of a different concept with instructions on how to update the presented script further below.

Pycharm Educational Edition

I love a hands on approach to learning new topics and this fits the bill rather well. You read the information, you follow the instructions and then click the tick box for feedback on if you have done it correctly or what you have done wrong so you can have another go or move on to the next topic.

I am also excited about the concept of other people creating learning courses that are available to the entire community using this tool so knowledge can be shared openly and freely, and usable offline too.

You can download this version of PyCharm here.

Summary

PyCharm is a very user friendly IDE for Python programmers. The Educational Edition is a brilliant way of giving people professional tools to learn a subject on which should help them progress to Python Jedi in a much shorter time frame.

Till the next time.