So you want to learn to program in Python and you don’t have a lot of time?
That’s okay! Once you grasp some of the key concepts and ways of thinking, it will all come to you.
So let’s get going now, shall we?
What is Python?
Python is a high-level, interpreted, object-oriented programming language with dynamic semantics used for general-purpose programming. It was created by Guido van Rossum and first released in 1991.
What is Python used for?
With Python being a general-purpose programming language, that means that it was created to to be used to perform common and everyday programming and automation tasks on a range of platforms and devices.
From shell/command-line scripts and tools, to desktop applications and even web application backends. In-fact, Python powers a lot of things around us everyday.
How to get started
Python is really easy to get started with. In-fact, it is probably already installed on your computer.
It comes in two main versions, 2.x and 3.x; of which 2.x (usually 2.7) is the one probably installed on your machine right now. There are a few differences between the versions but generally they are not that hard to move between when doing development.
A lot of the reason that a large proportion of developers are still using 2.x is because the third party software they rely on – or libraries they use – have not been converted to version 3.x yet, or they just don’t really care because “if it aint broke, don’t fix it!”..
I will try highlight and cover everything you learn below in both versions as best I can.
You can use the Python shell to experiment with python commands, but if you really want to do something bigger than a quick experiment, it is advisable to use a IDE (Integrated Development Environment) or your favourite text editor (Sublime Text or Atom Editor work well for this).
Create a blank text file and call it “pythonIsEasy.py”; notice the file extension “.py” is proprietary python.
You can now use the command-line/terminal to run your file as follows every time you make a change:
This will execute your python script in the python interpreter and perform any actions you have requested.
Lets get started now!
So what can you put in your Python file you ask…. Anything that is syntactically correct is the silly answer!
So let’s go over a few of the basics and then move on to more advanced topics a little later.
It is good practise to leave comments when you are writing code.
This is so that you can explain your way of thinking to another developer or even yourself a few months down the line.
There are two types of comments in Python;
Primitive Datatypes and Operators
Numbers are expressed as is, nothing strange or unusual here. That means that if you type in a number like 3, or 5 perhaps, it will be exactly that.
The same is true for maths in general.
It’s good to note that the division above (256/12) is floored before the result is returned/printed out. If you don’t already know, floor takes the floating point of a number to the lowest and closest whole integer number.
For example: 256/12 actually equals 21.333333333, but in Python, it equals 21.
If this is not what you are after, then we need to learn a bit about what floats are and how to use them.
In Python a floating number is simply an integer like 1, 2 or 3 with a decimal point added and an additional number, these numbers become floating numbers. For example: 1.0, 2.0 or 3.2 are floating numbers, or simply called floats.
So if we take this into account and repeat the above then we get:
The modulo operation finds the remainder after division of one number by another and as you might have guessed, it’s very simply to do in Python!
Exponents are easy too:
In maths you enforce order with parentheses (that means brackets)
It’s time to look at Boolean operators, which are essentially just variables that contain the value of True or False.
You can negate by adding the keyword not.
If you wanted to check if a variable was the same as another variable you would use double equals or == operator.
On the other hand, inequality is done with the != operator.
There are other ways to compare values, such as:
< Lesser than
> Greater than
<= Lesser than or equal to
>= Greater than or equal to
Notice how we went a little crazy and chained some comparisons above too!
If you want to store a name or similar, you would use a variable type called a String. In a String you can store any amount of alphanumeric characters. Notice the “ or ‘ at the start and end.
You can easily concatenate (add to) a String as follows:
You can also multiply Strings:
Every String is really just a collection of characters taking up a single space. That means that we can easily refer to a specific character in a String as follows:
If we pass our String into the len function, it will tell us how long it is!
Possibly one of the strangest things is the Object type of None. Yes, there really is a type of object called None.
Variables and Collections
Variables are so very important in any programming language. They are the thing that you store small amounts of data in, in order to then control the flow of an application and perform knock on actions down the line.
In Python you can print something to the screen using the print statement:
Here is our first example of where things are different between Python 2.x and 3.x. The above example will only work on 2.x, however the equivalent code below works only on 3.x.
Notice how print changed from being a statement to now being a function.
Oh, did I mention that you don’t need to even declare variables before assigning values to them? This is because the language is dynamic instead of strict like Java or C++.
There’s this thing called an Exception, which most programming languages have. They may seem foreign and can be quite annoying, but truthfully, they are one of your best friends.
They help you recover from your application crashing and provide a meaningful way of addressing errors as they happen.
Variable throw Exceptions too.
If we tried to access a variable that was unassigned, an exception would occur.
Ever heard of a ternary operator? It’s like an if else statement on a single line and it’s pretty cool!
In Python it’s called an expression and can be done as follows:
So we know how to store a number and a string, but what about a a list of items?
In Python we have a list variable type that allows us to store sequences.
We can easily add to them by using the append method.
Removing is done by popping the last item off the stack as follows:
Accessing an item in a list is easy, we just refer to it’s index; remember that everything counts from zero!
We can also reassign by their index as well:
If we refer to an index that doesn’t exist; then we get one of those lovely Exceptions we were talking about.
Now that we have a list to work with, let’s look at slices.
Slices sound complex but is a really simple way to retrieve a range of items from a list.
Let’s reset our list and add some data so we can see how slices work!
That last one was pretty cool! It reversed the list!
You can delete an item in the list by using the del keyword.
Just like all the previous variable types we’ve just seen, you can also add to lists.
It’s important to note that in the above example, list1 and list2 are never modified.
We use the remove function to remove items from the list.
You can use the in keyword to return a Boolean if an item exists within the list:
.. and you can also get the length (how many items) of the list:
It seems as though, that it is time to move onto a variable type called Tuple. They are basically the same as lists except immutable.
Immutable means that the state of the variable cannot change once it has been created.
So lists are good if you want to change them all the time, and tuples are good if you don’t want to change them after you’ve made them.
^ Hey look! ^^^ An exception was thrown… because… why??? Coz we tried to change an immutable variable! Can’t do that.. remember? 😉
Literally everything else is basically the same as lists… So let’s move along now.. Nothing to see here!
On that note, let me introduce a variable type called a Dictionary.
Sounds pretty complex, doesn’t it? Well.. it isn’t at all!
Dictionaries are great for storing mappings of things. Much like a JSON object if you are familiar with that.
Dictionaries are mutable (that means we can change them.. remember?)
That was easy.
Notice how the order of the keys was changed when we edited the dictionary though. (good to keep in mind)
There’s a couple basic functions you can use on dictionaries, such as “keys” and “values” as above.
Last but not least, I think we should take a look at a variable type called a Set.
Sets are basically exactly like lists, except they cannot contain any duplicates.
The control flow is so important in any programming language and Python is no different.
There are if statements which control which route the program should take.
Let’s create a variable we can do some things with.
Now we can do an if statement on this (let’s add in an else as well, while we’re at it):
Next we will try out a for loop.
They’re really easy actually:
Sometimes you just want to loop through a range of number:
If you set a variable outside of a function, it is not available within the function:
It’s simple to import modules.
One can even specify which functions inside a module to import:
This is great for when you know exactly what functions of a module you need and don’t want to pollute the stack space.
You can also alias modules during import as follows:
Modules are simply python files. So if you want to create your own, you just create files with the name you want to reference.
So now you know Python (mostly)! Congratulations!
One thing to remember about programming in general is that you are never done learning and you never know enough; in fact, this is only the start of your journey towards becoming proficient in the Python programming language.
A true software engineer is not someone who can create software in a specific language, but rather someone who understands how software works and fits together in any language or means of expression.
Now is a good time to go browse the Python website or go delve into it’s source code on Github.
Python strings as sequences of characters
Python strings are sequences of individual characters, and share their basic methods of access with those other Python sequences – lists and tuples. The simplest way of extracting single characters from strings (and individual members from any sequence) is to unpack them into corresponding variables.
Unfortunately, it's not often that we have the luxury of knowing in advance how many variables we are going to need in order to store every character in the string. And if the number of variables we supply doesn't match with the number of characters in the string, Python will give us an error.
Accessing characters in strings by index in Python
Typically it's more useful to access the individual characters of a string by using Python's array-like indexing syntax. Here, as with all sequences, it's important to remember that indexing is zero-based; that is, the first item in the sequence is number 0.
If you want to start counting from the end of the string, instead of the beginning, use a negative index. For example, an index of -1 refers to the right-most character of the string.
Python strings are immutable, which is just a fancy way of saying that once they've been created, you can't change them. Attempting to do so triggers an error.
If you want to modify a string, you have to create it as a totally new string. In practice, it's easy. We'll look at how in a minute.
Slicing Python strings
Before that, what if you want to extract a chunk of more than one character, with known position and size? That's fairly easy and intuitive. We extend the square-bracket syntax a little, so that we can specify not only the starting position of the piece we want, but also where it ends.
Let's look at what's happening here. Just as before, we're specifying that we want to start at position 4 (zero-based) in the string. But now, instead of contenting ourselves with a single character from the string, we're saying that we want more characters, up to but not including the character at position 8.
You might have thought that you were going to get the character at position 8 too. But that's not the way it works. Don't worry – you'll get used to it. If it helps, think of the second index (the one after the colon) as specifying the first character that you don't want. Incidentally, a benefit of this mechanism is that you can quickly tell how many characters you are going to end up with simply by subtracting the first index from the second.
Using this syntax, you can omit either or both of the indices. The first index, if omitted, defaults to 0, so that your chunk starts from the beginning of the original string; the second defaults to the highest position in the string, so that your chunk ends at the end of the original string. Omitting both indices isn't likely to be of much practical use; as you might guess, it simply returns the whole of the original string.
If you're still struggling to get your head around the fact that, for example, s[0:8] returns everything up to, but not including, the character at position 8, it may help if you roll this around in your head a bit: for any value of index, n, that you choose, the value of will always be the same as the original target string. If the indexing mechanism were inclusive, the character at position n would appear twice.
Just as before, you can use negative numbers as indices, in which case the counting starts at the end of the string (with an index of -1) instead of at the beginning.
Skipping character while splitting Python strings
The final variation on the square-bracket syntax is to add a third parameter, which specifies the 'stride', or how many characters you want to move forward after each character is retrieved from the original string. The first retrieved character always corresponds to the index before the colon; but thereafter, the pointer moves forward however many characters you specify as your stride, and retrieves the character at that position. And so on, until the ending index is reached or exceeded. If, as in the cases we've met so far, the parameter is omitted, it defaults to 1, so that every character in the specified segment is retrieved. An example makes this clearer.
You can specify a negative stride too. As you might expect, this indicates that you want Python to go backwards when retrieving characters.
As you can see, since we're going backwards, it makes sense for the starting index to be higher than the ending index (otherwise nothing would be returned).
For that reason, if you specify a negative stride, but omit either the first or second index, Python defaults the missing value to whatever makes sense in the circumstances: the start index to the end of the string, and the end index to the beginning of the string. I know, it can make your head ache thinking about it, but Python knows what it's doing.
So that's the square-bracket syntax, which allows you to retrieve chunks of characters if you know the exact position of your required chunk in the string.
But what if you want to retrieve a chunk based on the contents of the string, which we may not know in advance?
Examining the contents
Python provides string methods that allows us to chop a string up according to delimiters that we can specify. In other words, we can tell Python to look for a certain substring within our target string, and split the target string up around that sub-string. It does that by returning a list of the resulting sub-strings (minus the delimiters). By the way, we can choose not to specify a delimiter explicitly, in which case it defaults to a white-space character (space, '\t', '\n', '\r', '\f') or sequence of such characters.
Remember that these methods have no effect on the string on which you invoke them; they simply return a new string.
More usefully, we can garner up the returned list directly into appropriate variables.
Leaving our Spanish hero to his windmills for a moment, let's imagine that we have a string containing a clock time in hours, minutes and seconds, delimited by colons. In this case, we might reasonably gather up the separate parts into variables for further manipulation.
We might only want to split the target string once, no matter how many times the delimiter occurs. The method will accept a second parameter that specifies the maximum number of splits to perform.
Here, the string is split on the first colon, and the remainder is left untouched. And if we want Python to start looking for delimiters from the other end of the string? Well, there is a variant method called , which does just that.
Building a partition
A similar string method is . This also splits up a string based on content, the differences being that the result is a , and it preserves the delimiter, along with the two parts of the target string on either side of it. Unlike , always does only one splitting operation, no matter how many times the delimiter appears in the target string.
As with the method, there is a variant of , , that begins its search for delimiters from the other end of the target string.
Using Python's string.replace()
Now, back to our Don Quijote. Earlier on, when we tried to anglicise his name by changing the 'j' to an 'x' by assigning the 'x' directly to , we found that we couldn't do it, because you can't change existing Python strings. But we can get around this by creating a new string that's more to our liking, based on the old string. The string method that allows us to do this is .
Again, our string hasn't been changed at all. What has happened is that Python simply returned a new string according to the instructions we gave, then immediately discarded it, leaving our original string unaltered. To preserve our new string, we need to assign it to a variable.
But of course, instead of introducing a new variable, we can just reuse the existing one.
And here, although it may seem that we've changed the original string, in actual fact we've just discarded it and stored a new string in its place.
Note that, by default, will replace every occurrence of the search sub-string with the new sub-string.
We can control this extravagance by adding an extra parameter specifying the maximum number of times that the search substring should be replaced.
Finally, the replace() method is not limited to acting on single characters. We can replace a whole chunk of the target string with some specified value.
For references on the string methods used, see the following:
>>>a,b,c=s# Unpack into variables
Traceback(most recent call last):
ValueError:too many values to unpack
>>>s# Get the 5th character
Traceback(most recent call last):
TypeError:'str'objectdoes notsupport item assignment
'Quijote'# Returns from pos 4 to the end of the string
'Don '# Returns from the beginning to pos 3
>>>s[4:8:1]# 1 is the default value anyway, so same result
>>>s[4:8:2]# Return a character, then move forward 2 positions, etc.
'Qi'# Quite interesting!
>>>s[4::-1]# End index defaults to the beginning of the string
>>>s[:4:-1]# Beginning index defaults to the end of the string
'Don Quijote'# s has not been changed
>>>tim.split(':',1)# split() only once
'Don Quijote'# s has not been changed
>>>s.replace(' Qui','key ')