2. Getting started

It is customary for language tutorials to start with a plain "Hello World" and as such an adherent to tradition that I am, I will do no less:

In [1]:
print("Hello world")
Hello world

This should simply output:

Hello world

It is a very simple example where we pass the string "Hello world" to the function print which, well, print stuff (for those who don’t know, a string is sequence of characters, that is, a bunch of text).

We could make this a little more interesting, though:

In [2]:
somevar = "Hello world"
print(somevar)
Hello world

Which gets us the same output, but now, we first “store" the string inside the variable somevar, and then ask the function to print it for us.

Now let’s add some comments to our script:

In [3]:
#This is a Hello world in Python
somevar = "Hello world"
print(somevar)
Hello world

Just like bash scripting, everything that goes after # will be ignored by the Python interpreter. Now, lets try doing some math with integers:

In [4]:
someint = 12
someotherint = 23
somemath = someint + someotherint
print("Result:", somemath)
Result: 35

Which should simply output:

Result: 35

Note that the print function allows us to pass multiple arguments to it, and automatically concatenate them for us.

Now look at this other example using decimal numbers (called floats on Python).

In [5]:
somefloat = 3.43
someotherfloat = 1.4
amultiplication = somefloat * someotherfloat
print("Result:", amultiplication)
Result: 4.802

Which should output:

In [6]:
Result: 4.802

Let’s also try something more “complicated":

In [7]:
somefloat = 3.43
someotherfloat = 1.4
amultiplication = (3.24 + somefloat) * someotherfloat
print("Result:", amultiplication)
Result: 9.338

Which should output:

In [8]:
Result: 9.338

Note that, as your High School teacher always said, multiplication takes precedence over division:

In [9]:
somefloat = 3.43
someotherfloat = 1.4
amultiplication = 3.24 + somefloat * someotherfloat
print("Result:", amultiplication)
Result: 8.042

Which should output:

In [10]:
Result: 8.042

2.2. Exercises for delving deeper

You may now want to use the function type to check the type of those variables, like this:

In [16]:
somefloat = 3.43
someint = 1.4
somestring = "ske"
someotherstring = "2321"
type(somefloat)
type(someint)
type(somestring)
type(someotherstring)
type(someint + somefloat)
Out[16]:
float

Also note that none of these will work:

"2321" + 32
"2323.1" + 32
"2323" + 32.1
"2323.4" + 32.1

So, don’t try to add a string to an integer.