Introduction to Python
1. First Interaction

Python is a dynamicly-typed, interpreted language.

The best way to start using Python is to run the interactive Python interpreter and use it as a calculator. Assuming that you have Python installed in your system, you can run the interpreter by just typing "python" on a terminal.

$ python 
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

After you are in Python interpreter, you can use it as a simple calculator.

As you see Python is able to perform primary-school level mathematics. The interpreter reads an input from the user, evaluates it and prints the result to the screen. The expressions above are composed of numeric literals (integers, floating point numbers) and operators (+, -, *, /, %).

Now, assume that we would like to compute the area of a triangle using lengths of its sides with the following formula:

A = u(u-a)(u-b)(u-c)
Where
u = (a+b+c) / 2

For a triangle with sides a=3, b=4 and c=5, we can compute the area as follows (note that ** is the power operator):

Notice the redundant computations where we compute the half-circumference, u=(3+4+5)/2, four times. What we need is a way to store the value of "u" somewhere and use it several times without requiring to compute it again. This is where variables come to play.

Here we define a variable named "u" which stores the value of the half-circumference using the assignment operator "=". Then we use the variable in the expression that computes the area. Note that to display the value stored in "u" we write its name and press enter.

Now your turn: Define two variables named "foo" and "bar" which contain values 42 and 5 respectively. Then, define a third variable, named "ceng" which contains the result of division of "foo" by "bar".

Difficulty: 1 / 10
Home | About | Contact | Feedback