Learn Python in Fifteen Minutes
Lately I've dove into the world of Python. I had been hearing a lot of different things about it and about its many benefits and was curious what the buzz was all about. It's been a couple of years, at least, since I made it a goal to learn Python and just recently decided to take the dive and really get acquainted with it.
If you're a programmer and have heard of Python but haven't had the opportunity to give it a try but would like to know more about it, you've come to the right place. In a book I've been reading lately, The Basics of Hacking and Penetration Testing, I read about a concept called zero entry hacking. The idea behind zero entry is explained best with the analogy of a swimming pool where the water level starts at 0 feet and gradually gets deeper. This idea allows you to get in as deep as you feel comfortable but with little commitment of anything deeper. A zero entry lesson is what I will give you in this short post. You can read this post and say "yeah I get it, I'm going to go deeper" or you could simply say "I get it, good to know".
What is Python?
Without getting into a long history and concise explanation of Python, Python is simply a general programming language that is interpreted, portable, easy to learn, easy to write and has extreme power. Python can do just about anything the common languages can do such as C# and Java. The beauty of Python is that it does not require a complex development environment. All you need to write Python is a text editor and the Python interpreter. If you really want an IDE, you have several options such as Eclipse and PyCharm. among others. The beauty of Python is the productivity gains that you get compared to other general programming languages.
In order to begin using Python the first thing you must do is install Python. You can get Python from python.org. Once you have Python you can begin writing scripts. To install Python follow these instructions:
Installing Python on Mac OS
Installing Python on Linux
Installing Python on Windows
This tutorial is not about Installation though so please disregard any time you spend installing python against the 15 minutes.
To write your first program in open an editor, create a new file and type the following in the file
print "Hello World"Save the file as hello.py
In order to run your hello world program you must run the following command from the command line
*A prerequisite to running python is that you must add the path to python.exe in your PATH environment variable. If you don't know how to do this follow these instructions. In Mac OS or Linux you won't need to modify the path variable.
The Nitty Gritty
As promised, here are the basic fundamental concepts of Python. I hope that you already know how to program in a different language such as Java, C#, Ruby, etc. If you don't know how to program in a different language then this tutorial will not be as handy to you and you really need to take a full lesson on programming first. However, you can still get quite a bit of value by reading the post-programming section of this lesson.
Variables In Python
Variables in python, unlike, other languages don't require a declaration. You simply start using them by assigning them a value. For example:
*As a result of not having end of line character, Python has the / character to allow you to continue a statement onto the next line.
Condition Statements in Python
All high level languages require conditional branches for branching decision logic. In Python that is done with the use of the key words if, elif, else, and, or and not
age = 21 if age > 18: print "you are underage" elif age >= 18 and age < 21: print "you are an adult but not old enough to cosume alcohol" else: print "you are full blown adult"There a few things to notice about the above statement. First off, notice that there are three conditional blocks; if, elif and else. Second notice that all those statements require a colon at the end. Thirdly the scope of each statement is determined by the indentation of the lines with each condition block.
In this case I decided to use 3 spaces for indentation. As long as you use the same indentation after one of those conditions that line will be part of your block. Changing the indentation does not necessarily jump of of the block, instead it will result in a syntax error. You can use a different number of spaces than 3 but the key thing is that all lines within the block must use the exact same number of spaces. This is how python determines what is in the body of that code block. That also applies to functions which we will get into in a few moments.
Here is a quick example of a function. This particular function takes in two arguments, x and y, prints the values of x and y and then returns their sum. The print statement then calls add with 5 and 6 as the parameters.
def add(x, y): print x print y return x + y print add(5,6)
In this simple function definition you can see how a function is declared and then called. Notice that the function signature does not declare a return type. That is determined by the return statement (return x + y). That function could just as easily have returned nothing instead and it would be valid except that the the print line would not have anything to print since the add function had no return value. The code would still work but the output would be "none".
Here are some examples of loops in python. Once again notice the indentation and the termination using the colon character. All code that belongs inside the loop block must use the same number of spaces for the indentation. As long as the indentation is the same all code will be part of the loop.
names = ['joe', 'mary', 'jane', 'michael'] print "\r\nforeach equivalent" for name in names: print name print "\r\nfor equivalent" for i in range(0, 3): print names[i] print "\r\nwhile loop" j = 0 while j < 4: print names[j] j = j + 1
Each of these loops prints the names within the names list. The first loop is similar to the foreach loop in C#. It automatically assigns a value to the variable name from the list of names. The second for loop uses the range function to store a value from 0-3 in the i variable as it loops through the names. It then uses that value as the index to the values in the names list.
The while loop just uses standard loop functionality by incrementing the value of j and then using that as the index to a name within the names list.
In python you can re-use code through the use of modules. A module is simply a file that contains code that can be called from other code. Modules can have classes or other functions. To import a module you simply use the import keyword. You can see this in the example below.
import math print math.floor(9.4) print math.ceil(9.4)
The code above would print 9 and 10 using math.floor and math.ceil respectively. The code above is using the functions floor and ceil that can be found in the math module. The functions floor and ceil are defined in the the file math.py.
You can write your own modules too. For example we could write the add function from the Subroutines function and save it as adder.py. We could them call it by importing adder:
import adder print adder.add(5,6)
Just make sure to not keep only definitions in your modules and calls to other modules that are not wrapped inside function calls because the code in a module is executed from top to bottom. Function defintions are not executed because they are definitions but other function calls such as print outside of a function definition will be called. For example the print(5,6) in the Subroutines section would be called at runtime whenever the module was imported.
No introductory tutorial to python would be complete without a mention of Collections. Lists, the primary collection of python, are at the heart of Python and are very handy for well handling collections of items. You have already seen your first example of a list in the loop section of this tutorial. I won't get into all the details of Lists. I will simply say that there are different types of collections in python, as you would expect. There are lists, queues, dictionaries and tuples. Lists can behave as stacks. Here is a quick example of a list being manipulated.
listOfNames = ["jack", "jill", "jane"];
In this example the list starts out with 3 names; jack, jill, jane and it appends "joe" to the end of the list. Finally the list gets "jeff" inserted at the beginning.
If you made it this far and want to learn more about collections let google be your friend in using sets, dictionaries, queues and stacks (a list used as a stack).
Object Oriented Programming
A class in python is very easy to define
class Employee: def __init__(self, name): self.name = name def sayName(self): print self.name employee = Employee("Jack"); employee.sayName();
The __init__ (underscore underscore init underscore underscore) method in a Student class is the constructor for the class. The class variables by default are equivalent to static variables unless they prefixed with __ (underscore underscore). Notice how although the self is declared in the methods of a class they are implicitly set by the instance of the class. The instantiation of employee is outside of the class definition due to the change in indentation.
Python has full capabilities for inheritance and polymorphism but I will leave that up to you if you want to dive deeper into the language.
Power of Python
Out of the box, python has several modules that will allow you to do common things such as
- String Manipulation
- Numerical and Mathematical modules
- File and directory access
- Data Compression
- Configuration File Manipulation
- Cryptographic Services
- Parsing Command Line Arguments
- Reading from and writing to files
- Operating System Services (threading,)
- Interprocess Communication and Networking
- Internet Data Handling (email, base64 encoding, json, etc)
- Structured Markup Handling(HTML, XML, etc)
- Internet Protocol Handling (CGI, FTP, POP3, etc)
- Multimedia(video, audio)
- Graphical User Interfaces
- Development Tools (Unit Testing, documentation generators, etc)
- Windows Specific Services (Registry access, Sound playing for windows)
- Unix Specific Services
- Mac OS X Specific Services
The functionality in this list is from the modules that Python ships with. Numerous other third party libraries exists that allow you to do even more powerful things. You can look through the official list of python library at the python website. Anything you can think of doing is easy to do, all it takes a short google search and a few hours of work at most.
What kinds of things can I do with Python?
Just from the list above in the Power of Python you can probably guess that there is little that you can't do with Python. Some of the things that Python is ideal for are:
- Automation - You can easily automate the boring and repetitive stuff with ease. With so many modules available you can likely download a module and tackle a task in a few others that would take days or weeks with C# or Java.
- Penetration Testing- Python is popular for penetration testing because it is extremely easy and productive for this sort of thing.
- Forensics - An introduction can be found to the how is demonstrated in the book Violent Python
- Raspberry Pi - Since python runs with easy on any platform it is ideal for the raspberry pi in combination with Linux.
- Games - There is a website dedicated to creating games with Python at pygame.org
- Control Language - Python can be leveraged to control processes. This makes me wonder how Python would compare with something like PowerShell. At a minimum it would be more universal since PowerShell is Windows specific and python is not. I hear that Python can be used to replace bash scripts and it is much easier to maintain than the bash code.
- Windows Applications
- Web Applications
Python is a much simpler language with less rules than a language such as Java or C#. Programs can be written with less effort and fewer lines. There is not expensive setup necessary to begin writing python scripts. C# requires Visual Studio (not exactly but I don't know too many people that write C# in a plain text editor). Java works best with Eclipses or some other IDE. Python requires none of that. Although it works quite well with Eclipse, it is much easier to setup than something like Java. Scripts can be fixed quickly and easily.
In a recent video I heard a speaker say that he hears employers say "I can't find any Python programmers". His response to this is to take any good programmer in any language and you can have a good Python programmer within a week. Python is extremely easy to learn.
So perhaps you feel that my post is misleading because you are not a Python expert as you finish reading this. However my point is that if you already know another language you can easily start writing real working solutions with the simple tutorial I just provided. Sure there are always some nuances as you dive into a new language, but that is expected.
It wouldn't be fair to say that Python can replace those other languages. I've only begun scratching the surface with Python. I simply don't know enough to make that call. Python is interpreted and it won't be as fast a language like C. However it can be combined with another language like C and delegate the hardcore processing to C. There are also variations to Python such as Jython that can call Java code directly. So the more hardcore functionality can be handed to Java if necessary.
It seems that Python will even allow it to be a back end language with frameworks like Django and TurboGears. So as I learn more about Python I have to really dig and find out what the trade offs are over other languages.
Please feel free to comment below. I welcome all comments. Please subscribe on the email box below to receive weekly updates. You can also follow me on twitter @fernandozamoraj.