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.
On Windows:
Click Start -> Run
Type "cmd", hit "Enter"
Type "python", hit "Enter"
If that doesn’t work, then go here and download Python first: https://www.python.org/downloads/windows/
**
On Mac/Linux:**
Open a terminal window and type "python", hit "Enter"
Running Python
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:
python pythonIsEasy.py
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.
Comments
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;
Single-line:
# Single-line comments always start with the hash symbol
**
Multi-line:**
""" Multi-line comments always start and end
with three "s, this indicates that anything in-between
is a comment and should be ignored by the interpreter"""
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.
>>> 1+2
3
>>> 3-4
-1
>>> 8*32
256
>>> 256/12
21
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:
>>> 256/12.0
21.333333333333332
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!
>>> 2%1
0
>>> 18%12
6
Exponents are easy too:
>>> 2**2
4
>>> 5**3
125
>>> 10**10
10000000000
In maths you enforce order with parentheses (that means brackets)
>>> 1+2*3
7
>>> (1+2)*3
9
It’s time to look at Boolean operators, which are essentially just variables that contain the value of True or False.
>>> True
True
>>> False
False
>>> True and False
False
>>> True and True
True
>>> False and False
False
>>> 1 and True
True
>>> 2 and False
False
You can negate by adding the keyword not.
>>> not True
False
>>> not False
True
If you wanted to check if a variable was the same as another variable you would use double equals or == operator.
>>> 1 == 1
True
>>> 2 == 3
False
>>> True == False
False
>>> True == 1
True
>>> True == 2
False
On the other hand, inequality is done with the != operator.
>>> 1 != 1
False
>>> 2 != 3
True
>>> True != False
True
>>> True != 1
False
>>> True != 2
True
There are other ways to compare values, such as:
< Lesser than
> Greater than
<= Lesser than or equal to
>= Greater than or equal to
>>> 1 < 2
True
>>> 1 > 2
False
>>> 12 <= 12
True
>>> 3 < 4 > 5
False
>>> 18 >= 12 < 18
True
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.
>>> "This is a String"
'This is a String'
>>> 'This is also a String'
'This is also a String'
You can easily concatenate (add to) a String as follows:
>> "This is a "+"String"
'This is a String'
>>> 'This is also'+" "+"a "+"String"
'This is also a String'
You can also multiply Strings:
>>> "Hello " * 4
'Hello Hello Hello Hello '
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:
>>> "Strings are pretty cool"[0]
'S'
>>> "Strings are pretty cool"[8]
'a'
If we pass our String into the len function, it will tell us how long it is!
>>> len("Strings are pretty cool")
23
Possibly one of the strangest things is the Object type of None. Yes, there really is a type of object called None.
>>> None
>>> False == None
False
>>> True == None
False
>>> False is None
False
>>> True is None
False
>>> None is None
True
>>> 1 == None
False
>>> 0 == None
False
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:
>>> print "Hello there!"
Hello there!
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.
>>> print("Hello there!")
Hello there!
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++.
>>> myVariable = 13
>>> myVariable
13
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.
>>> thisVariableDoesntExist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'thisVariableDoesntExist' is not defined
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:
>>> "Hello World!" if 2 > 1 else 1
'Hello World!'
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.
>>> list = []
>>> list
[]
>>> list = [1, 2, 3]
>>> list
[1, 2, 3]
We can easily add to them by using the append method.
>>> list.append(4)
>>> list
[1, 2, 3, 4]
Removing is done by popping the last item off the stack as follows:
>>> list.pop()
4
>>> list
[1, 2, 3]
Accessing an item in a list is easy, we just refer to it’s index; remember that everything counts from zero!
>>> list[0]
1
>>> list[1]
2
We can also reassign by their index as well:
>>> list[0] = 9
>>> list
[9, 2, 3]
If we refer to an index that doesn’t exist; then we get one of those lovely Exceptions we were talking about.
>>> list[99]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
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!
>>> list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[1:4]
[2, 3, 4]
>>> list[4:]
[5, 6, 7, 8, 9]
>>> list[:4]
[1, 2, 3, 4]
>>> list[::4]
[1, 5, 9]
>>> list[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
That last one was pretty cool! It reversed the list!
You can delete an item in the list by using the del keyword.
>>> list
[1, 2, 3, 4, 6, 7, 8, 9]
Just like all the previous variable types we’ve just seen, you can also add to lists.
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> list1 + list2
[1, 2, 3, 4, 5, 6]
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.
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list.remove(3)
>>> list
[1, 2, 4, 5, 6, 7, 8, 9]
You can use the in keyword to return a Boolean if an item exists within the list:
>>> list
[1, 2, 4, 5, 6, 7, 8, 9]
>>> 3 in list
False
>>> 2 in list
True
.. and you can also get the length (how many items) of the list:
>>> len(list)
8
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.
>>> tuple = (1, 2, 3)
>>> tuple
(1, 2, 3)
>>> tuple[1]
2
>>> tuple[1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
^ 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.
>>> dict = {"hello": "dictionary", "world": "my old friend"}
>>> dict
{'world': 'my old friend', 'hello': 'dictionary'}
>>> dict["hello"]
'dictionary'
Dictionaries are mutable (that means we can change them.. remember?)
>>> dict["hello"] = "oh hi!"
>>> dict
{'world': 'my old friend', 'hello': 'oh hi!'}
>>> dict["hello"]
'oh hi!'
That was easy.
Notice how the order of the keys was changed when we edited the dictionary though. (good to keep in mind)
>>> dict.keys()
['world', 'hello']
>>> dict.values()
['my old friend', 'oh hi!']
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.
>>> our_set = set([1, 2, 3, 4])
>>> our_set
set([1, 2, 3, 4])
>>> our_set_2 = set([1, 2, 2, 3, 4, 4])
>>> our_set_2
set([1, 2, 3, 4])
Control Flow
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.
some_number = 7
Now we can do an if statement on this (let’s add in an else as well, while we’re at it):
>>> some_number = 7
>>> if some_number > 3:
... print "It is bigger!"
... else:
... print "It is not bigger :("
...
It is bigger!
Next we will try out a for loop.
They’re really easy actually:
>>> for food_item in ["pizza", "toast", "watermelon"]:
... print food_item
...
pizza
toast
watermelon
Sometimes you just want to loop through a range of number:
>>> for i in range(3, 13):
... print i
...
3
4
5
6
7
8
9
10
11
12
If you set a variable outside of a function, it is not available within the function:
>>> a = True
>>> def test():
... print a
...
Modules
It’s simple to import modules.
import math
>>> print math.sqrt(100)
10.0
One can even specify which functions inside a module to import:
from math import sqrt
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:
import math as m
Modules are simply python files. So if you want to create your own, you just create files with the name you want to reference.
What’s Next?
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 its source code on Github.