|
Écrit par JLangbridge
|
|
Mardi, 15 Mai 2012 12:15 |
The Basics
So welcome to Python! This tutorial assumes that you have correctly downloaded and installed Python for your computer. So, what is the first step? When most of us think about programming languages, we imagine people typing in hours and hours of obscure code into a window, then it all magically runs with flashing lights, soft of Hollywood style. Forget about that. Normally, with most languages, it does start off with a blank page, and writing in structural code, imagining what could happen. There are lots of tools afterwards; compilers, emulators, debuggers. Python has an even simpler solution, the command line.
The Python command line is a mix between a normal terminal and a blank page. This is a playground, where you can test anything, in real time! So let's try. Fire up a Python command line. In Windows, it is in the Start menu, Python, Python Command line. On Linux, open a terminal and type "python". You should be greeted with something that looks like this:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSV v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "licence" for more information.
>>>
If that is what you have, congratulations! You are ready to have fun. Don't worry about the figures, or the date, etc. You might not have exactly the same version, or it might have been created at another date. So long as you have something that looks like the above. If you can't run it, double check your Python install.
Programming language basics
Any compter language will depend on a few things. Most of this will be common to any programming language, ahtough some may implement them differently. Remember, a computer program is a list of instructions given to a computer, telling it to do certain tasks. Some may be simple, others may be horrendously complex, but they are all based on the same things.
Variables
A "variable" is a space in memory used to hold some data, that can be retrieved later on. The name "variable" implies that the value can be changed, and indeed, it can. Some other programming languages have "constants"; they are the same as variables, except they cannot be changed. For Python, we only have variables; memory locations that can hold data for us. The data can be just about anything; a number, a letter, a name, an Internet site link, a picture... All of this can be saved as a variable. To create a variable, we need two things; a variable name, and a value. Lets go ahead and create our first variable:
score = 87
Hit enter. You will have a new line, starting with ">>>", just like before. Python doesn't tell us anything about what we have just done; if there isn't an error message, we can assume that everything went well. Don't worry, Python will warn us if something goes wrong.
At this point, people coming from the world of C and C++ will begin to have a heart attack. Contrary to several languages, with Python, you don't need to "declare" a variable. Before using it, you do not need to tell the compiler what the name is, and what type it will be. For example, in C, we can often see something like this:
int i; char buffer[255]; float fDistance;
This defines 3 variables; and also tells the compiler what sort of data we can put into these variables. fDistance will hold a float; a value with large precision after the decimal point. Don't worry about this in Python; you don't need to tell Python what you will put in there. You don't even need to tell it before hand that you will be using a particular name. The Python interpreter will happily use whatever you give it. In our case, we have used the name "score", and assigned it the decimal value 87. We can assign it another number, or even give it some text, and why not even a JPEG image? Anything is possible. Let's continue our game. The user has just got another point, so let's add it:
score += 1
This takes the value of our variable score, and adds one to that value. The game carries on for a few minutes, and we've lost track of the score. Let's just ask Python what the score is:
score
And the Python interpreter answers 88.
It's the end of the game, and we've got a high score! In order to boast about it, we need to save the player's name. Let's create another variable; player
player = "My name!"
Now the variable player has some text assigned to it, but what happens if we make a mistake? We know that a variable can hold just about anything, and we can change the data type, what happens if we try to add one to something that isn't a number? Let's try.
>>> player += 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
Here we go; we tried to add a number to a string, and Python is complaining. So what could we have done about that? We might not remember (or even know) what the data type is, but Python does. Let's ask it what the type is:
>>> type(player) <type 'str'> >>> type(score) <type 'int'>
"player" is a str, or string. 'score" is an int, or integer. Now we know what to expect. To sum it up, we can put just about anything we want into a variable, and we can fetch that data later on, and even know what type it is.
Coding style
We now know about variables, but there is a lot more we can do with Python. We can make decisions on thos variables; if our score goes beyond 100, we might want to add another enemy player onto the board to make things more difficult. If the player name was already entered, we might want to look up his old score, and replace the previous value. In order to do this, we will be using conditions, control flow and functions. Before doing so, we need to talk about coding style. In most languages, it doesn't really matter how you write your code visually, the interpreter will read it, no matter how ugly, and compile your program. Some people even make their code as ugly as possible, for more information see the International Obfuscated C Code Contest. Some of their examples have been used for case studies, because they really are unreadable, and very few people can actually understand what is going on. You won't see any Python code in that sort of contest; Python is made to be visible. In C, different portions of code are written between accolades, so the interpreter knows what we want. With Python, we use text formatting. Consider this code from the Python website:
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def overdrawn(self):
return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance
Don't worry if you can't understand the actual code; we will be going into that later on. For the time being, concentrate on the structure. The first line, "class BankAccount(object), creates a "class", an "object". The next few lines are indented; all of the indented lines belong to the class. The indentation is the interpreters way of knowing what belongs to what. the line "def __init__" belongs to the class BankAccount, just as the next line, "self.balance = initial_balance" belongs to the def __init__. Further down, we see "my_account = BankAccount(15). This line is indented in the same way as the class BankAccount, so this line does not belong to that class. The good side is that it makes Python code easily readable, but the bad side is that you need to pay attention to what you write and how. In this example, we use four spaces to indent our code. Later on, if we attempt to use only three spaces to indent, we will get an error, since the interpreter will not understand what we want. Don't worry, it is a lot easier than it sounds, and later on it will become second nature to you.
In our previous examples with variables, we didn't need to indent, since we wanted the interpreter to execute every line that we gave it. That is about to change; we are about to have some real fun! Now that we know how to write good looking code, let's learn how to have some fun!
|
|
Mise à jour le Mercredi, 17 Octobre 2012 14:58 |
|
Écrit par JLangbridge
|
|
Mercredi, 25 Avril 2012 12:07 |
Tutorial 1 - The origins
Python was concieved in the late 1980s by Guido van Rossum. It was designed as a replacement for the ABC language, and was used primarily on the Amoeba operating system.
Standard Library
Like almost all programming languages, Python comes with a Standard Library, meaning a cookbook of routines and functions allowing you to do just about anything from mathematical operations to file input/output, ZIP compression to networking. Python has a beautifully modular approach, with the basic philosophy of "If you need it, it is there. If you don't, you don't have to include it. If you need it but it isn't there, you can add it". As such, there are hundreds (if not thousands) of "modules" available for Python that increases functionality. A few examples of that are Twisted, allowing event-driven networking, NumPy, for scientific calculation, PyGame for making games using Python, and PIL, the Python Imaging Library. The list goes on and on, but those are just a few.
But who uses Python?
It doesn't matter how nice a programming language is, if no-one uses it, it is doomed. Fortunately, Python is in no risk of being forgotten, since some major actors use it. The Python wiki keeps an up to date list of some of them, here is just a small extract: Yahoo Maps, Yahoo forums, Google (extensively), Battlefield 2, Civilization 4, Industrial Light and Magic, Walt Disney Feature Animation, The National Research Council of Canada, NASA, etc etc...
Python is fun!
Python's name is derived from the television series Monty Python's Flying Circus, and you can find a lot of Monty Python references in example code and tutorials. Python is designed to be powerful, but it is also designed to be fun, and that is where the name comes in. Try it, you'll have lots of fun with it!
Python is easy for beginners
Python is known to be a very easy programming language to start off with, as well as a powerful tool for more experienced programmers. Python is designed to be easy to read, and the maintainers refuse to trade readability for anything else. Small optimizations that would speed up the language but make it less readable are normally rejected. A Python program is easily readable, and comprehensible. While some programming languages might be synonymous to black magic, Python programs are readable and understandable. There is also a complete debugging suite included directly into the language, making the debugging process painless. Don't be afraid of the word "debugging"; sooner or later everyone ends up debugging, but with Python, it's fun!
Python is interpreted
As far as programming languages go, there are 2 main categories; compiled, and interpreted. Python is an interpreted language. An interpreted language is a language where programs are indirectly executed, which has advantages and tradeoffs. The most notable traseoff is that since Python programs are run by an "interpreter", they can be slower than native machine-code programs, but don't let this frighten you, Python is still very fast! While machine-code programs may be faster, they are also tied to one particular platform, which isn't the case for Python. The same Python program can run on Windows, Linux, MacOS... Maybe even some mobiles phones and embedded systems. Python is portable!
Versions
Version 2.0 of the Python programming language came out in 2000, with many new features such as garbage collection and the support for Unicode. If this doesn't mean anything to you, don't worry. You can dig into Python all you want to find out as much detail as you want, or just skim the surface and use Python for your own projects and needs, that's fine. Today, in the version 2 branch, most people use 2.6 and 2.7. In December 2008, version 3.0 was released, and it made a lot of noise. It added a lot of new features, of course, but it also changed one thing, it became backwards incompatible with Python 2.x. Anyone starting a new project today needs to ask the question, should I use Python 2 our Python 3? The answer isn't always that easy. It depends greatly on any modules that you might need. Some modules are built for Python 3.0, but others will only work for the 2.x series. My tutorials will concentrate on the 2.x series.
|
|
Mise à jour le Mardi, 15 Mai 2012 12:15 |
|
|
The Python programming language is one of those languages that has made a huge impression on the developer community. Python programmers like to consider the Python programming language as "batteries included", since you can do practically anything with the standard library. Python is easy, Python is fun, and Python can do just about anything you want it do to. In this series, I will explain a little more about the language, and show you just what can be done with it.
You may well have heard about Python, but what exactly is it? What can you do with it, and what are the questions you need to ask yourself before diving in? Read more here.
Let's run through a few lines of code, and see what happens
Tutorial 3 - Python as a calculator
Computers were designed to crunch numbers. Let's see how we can do that with Python!
|
|
Écrit par JLangbridge
|
|
Jeudi, 09 Février 2012 16:21 |
|
QT has been making some noise for quite some time. The very first version of QT was designed all the way back in 1991, and at the time had two variants; Qt/X11 and Qt/Windows. When I started graphical Linux, in 1997, I had a "choice" between Gnome and KDE. KDE 1.0 wasn't out yet, but it was very promising, and it used the Qt framework. For a lot of personal reasons, I eventually went with Gnome, even though today I'm more of an XFCE fan. While I wasn't looking, Qt went ballistic.
While Qt was originally released for 2 platforms, today it is dominant in the multi-platform domain. Major players are using it, to cite but a few, we have Google, HP, Walt Disney Animation Studios, DreamWorks, and of couse, KDE. The advantages are of course portability; create an interface, and use it with just about any system and almost any language. Qt bindings exists for C++, Java, PHP, R... And of course, Python. Numerous frameworks exist to add Qt support in Python, but the one I've chosen to look at is PySide.
A simple Hello World application looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/python
# Import PySide classes
import sys
from PySide.QtCore import *
from PySide.QtGui import *
# Create a Qt application
app = QApplication(sys.argv)
# Create a Label and show it
label = QLabel("Hello World")
label.show()
# Enter Qt application main loop
app.exec_()
sys.exit()
|
In this basic application, we have everything we need to correctly set up a basic application. With PySide applications, we need to import PySide.QtCore and PySide.QtGui classes, since they have the functions necessary for building PySide applications. We create the QApplication, create a simple QLabel and set it up, show it, then we are ready to run our application. Simple!
|
|