Introducing Python
Pure awesomeness
Python is one of the most popular languages out there these days. Its easy to learn and suitable for a lot of different purposes, from small and quick scripts to large massive projects. So, just like I did with Ruby before I will do with Python now to give you a nice and quick introduction.
Python comes bundled with most, if not all Linux distributions and its quick to set up on Windows as well. This tutorial will assume you have Python installed properly.
Python features an interactive shell that lets us evaluate Python code on the fly, so lets take our first steps in there. Start by opening your terminal or command prompt and type python
We will start with the inevitable “hello world” app. All we need is the following code.
print "Hello World" |
Thats all we need to print out “Hello World” to the terminal window. However, this is rather boring so lets expand it a bit by putting our line of code into a function. Instead of typing this directly into the Python shell, create a new file called hello.py and type in the following.
#hello.py def hello(): print "Hello World" return hello() |
Now save and run the file from your console by typing python hello.py
We have now defined a function called hello() and we run it by calling the function which we do on the last line. Simple stuff right? Putting our code into functions like this is rather useful, especially for longer pieces of code.
Functions can also take parameters. Our hello() function currently doesnt take any, but how about we give it one?
#hello.py def hello(name="World"): print "Hello %s" %name return hello("Python") hello() |
Our function now takes a parameter, name, and uses this when it prints out the string. Notice how we use %s. It indicates that we will be substituting %s with a string variable. If our parameter was a decimal number we would use %d. Python supports several datatypes. Python also handles these automatically. Meaning when you define a variable you dont have to specify what datatype it is going to be as Python will figure it out for you. The problem occurs when Python gets it wrong, but we will get back to that later. Also notice how we set a default value for the name-variable, so that if we call the function without passing the name-parameter, it will be set to “World”. We can of course also reference multiple variables in a given statement.
#hello.py def hello(name, age) print "Hello %s, you are %d years old" %(name, age) return hello("Gordon", 34) |
Speaking of variables, lets take a closer look at them. As mentioned a variable has a datatype but with Python you dont normally have to specify what the type a given variable is, as it can figure it out for you. Lets take a few examples.
String
my_name = "Bob" |
Integer
my_botnetsize = 22500 |
List and tuples
my_hobbies=['hacking', 'cracking', 'phreaking', 'phising'] |
my_languages=("assembly, "c", "c++") |
Dictionary
my_tools={"scanner":"nmap","rootkit":"HackerDefender","editor":"vim"} |
String variables can be manipulated in a number of ways. We can add a string to an existing string.
my_name="Bill" my_name += " Gates" |
We can split a string which will return a list of elements.
namestring="Bill.Bob.Bobby.Barry.Bobilicious namestring.split(".") |
We can modify the characters by using upper(), lower(), capitalize() and many more..
my_name.upper().lower().capitalize() |
Lastly, we can cast a variable into a string. Like an integer for example..
my_age=str(50) |
Integers are handled the same way as most other high level languages. Meaning you can easily increment, add and subtract as you see fit.
num = 10 num += 10 num -= 2 print num 18 |
We can also take a number which is defined as a string and cast it to an integer.
numstr = "10" print int(numstr)+5 |
Lists and tuples are also very useful especially when you utilize the functions you can apply to them.
You can assign variables to elements in a list
ftpcon = ["ftp.url.com","user", "pass123"] host, username, password = ftpcon |
We can join elements in a list to form a new string
my_shows=['The Wire', 'The Firm', 'Game of Thrones'] print ",".join(my_shows) The Wire, The Firm, Game of Thrones |
In addition to join, we can use sort(), pop(), remove(value), insert(i, value), append(value), and many many more.
You can also retrieve specific elements. In the following example we start printing out from the second element in our list.
print ftpcon[1:] ["user","pass123"] |
Oh, and in case I forgot to mention it, the difference between a tuple and a list is that a tuple is a list that cannot be changed. So basically a static list.
Now that we have a handle on the concept of functions and variables, lets expand a bit and look at classes. If you are familiar with other high level object based programming languages, Classes should be easy to understand. So lets throw some code at you and see if you can follow.
#hello.py #Define the class HelloClass (new style) class HelloClass(object): #Constructor def __init__(self): self.__name = "World" #Defining the sayhello function def sayhello(self): print "hello %s" %self.name #Defining the saybye function def saybye(self): print "bye %s" %self.name #Create a new HelloClass object hello = HelloClass() hello.name = "Edvard" #Run the sayhello function hello.sayhello() #Run the saybye function hello.saybye() |
We have here defined a new style class. New style classes were introduced in python 2.2. A new-style class is a class that has a built-in as its base, most commonly object. At a low level, a major difference between old and new classes is their type. Old class instances were all of type instance. New style class instances will return the same thing as x.__class__ for their type. Since the old style is gone in Python 3, all aspiring developers should be using the new style.

Pingback: Introducing C – Connect-UTB