Did you know: programmers convert coffe to code?

If you like my articles, support me with a small amount.


Buy me a coffee

Python basics — a.k.a. “Hello World!” and how to achieve it

After the introduction and installing Python let’s jump right ahead and write the first lines of code with Python 3.

The first step is to fire up the interactive interpreter with the python3 command. The three arrow-heads (or greater signs) indicate the prompt where we can type in our commands for the interpreter. We will type in the following text: “print(‘We want a shrubbery!’)” and hit return.

This article is an excerpt of my book Python 3 in Anger. For a more detailed version take a look at the book.

The following code snippet shows what you should see:

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('We want a shrubbery!')
We want a shrubbery!

This is the basic Python application which prints the given string to the console. Basically we will use the print function to write all of our messages to the console.

Basic syntax

The basic syntax of Python is very similar to other programming languages. There are however some differences which can cause troubles when developing applications.

So let’s examine the basic syntax for Python applications.

Indentation

This is the most disturbing thing you can encounter. This can give you sleepless nights later on if you do not configure your IDE right — or extend code written by others with other formatting settings.

But what does indentation mean?

Most widely used programming languages utilize curly braces ({}) when executing statements grouped together into blocks. Python utilizes indentation because so the code gets more readable. Let’s demonstrate it with a little example:

if(a == 42){a = 25; System.out.println(a);}else{a = 42;}
if a == 42:
a = 25
print(a)
else:
a = 42

As you can see the Python code is more readable (it is my opinion although I am a well-grounded Java developer too so I could rewrite the previous example to be readable). And if you have an indented line it means that it belongs to the same execution group. In Java for example it won’t:

if(a == 42)
a = 25;
System.out.println(a);
else
a = 42;

Without using the braces you will get a SyntaxError because in the case above the System.out.println(a); does not belong to the if statement.

However this is not an article about Java or differences between these two programming languages so I return from this errand to the topic of indentation.

Why can it cause sleepless nights? Because you have two ways to indent: with spaces or with tabs. And you mustn’t mix up both! If you do, you get a TabError:

>>> a = 33
>>> if a == 42:
...     a = 25
...     print(a)
File "<stdin>", line 3
print(a)
^
TabError: inconsistent use of tabs and spaces in indentation

It is not visible in the example above but first I used spaces then a tab to indent the line. This causes the exception.

If I switch the lines I get an other error:

File "<stdin>", line 3
a = 25
^
IndentationError: unindent does not match any outer indentation level

And this is what I mean by sleepless nights. If you mix the things up then you have to look through the file and find every possible place where you interchanged spaces with tabs or vice versa.

Comments

Commenting the code is sometimes necessary (although some developers say that if you have to write comments to describe your code you should re-write the code).

You can do it with a hashtag (#). This tells the interpreter that the writings on the same line after the hashtag are only comments, they are not meant to execute:

>>> print(1+2) # results in 3
3

Note that there are no multi-line comments as in other programming languages. If you want to disable a block of code you have to put a # at the beginning of each line.

Identifiers

An identifier is a name to identify a variable, a class, a function, a module or other objects.

In Python you can start the identifier with a letter (upper- or lowercase does not matter) or an underscore (_) and can be followed by zero or more letters, numbers and underscores after it. Punctuation characters (like @, $ and %) are not allowed in identifier names.

The language is case sensitive, this means that you can have a variable called my_variable and another called My_variable and they would be treated as different variables. So take care because this can cause problems too when developing.

Reserved words

A high-level programming language is almost a free-form writing of code. However there are some internal words which are reserved for special use-cases and they have a meaning for the interpreter when it encounters them.

This means you cannot use these keywords as identifier names. In other case you get an error depending on the keyword.

False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

And of course they are case sensitive. This means you can use false as a variable name but not False.

User input

Programming gets fun when you can write interactive applications. Interactivity means that a user can enter some input to the application and he/she becomes an answer to it.

I’wont start here to write applications with user input for now but I’ll tell you how you can ask the user to provide something.

It goes with the input function and is very simple to use:

>>> entered = input("Enter some text: ")
Enter some text: 42
>>> entered
'42'

As you can see, you can pass along a parameter to the input function and this parameter gets displayed as a command prompt for the user. After he/she enters something it is stored in the entered variable as a string.

Later we will examine the input functionality more thoroughly.

Basic operators

Now it is time to have a look at basic operators which are available in Python. I know it is not much of a use without knowing the basic types but hey! We already know that there are at least numbers and strings in the language and this is a very good starting point for operators.

Arithmetic operators

Everyone knows them, they are the base of mathematics. So Python has to know them too. They work with variables too if they are from the right tpye. This means you cannot use addition on a number and a string for example.

Let’s go them through fast with some examples. I hope the examples explain themselves. If you find tis is not the case feel free to write me a message and I’ll add explanatory text to the examples too.

>>> 6 + 5 # the + sign adds numbers up
11
>>> 6 - 5 # the - sign subtracts the second number from the firs
1
>>> 6 * 5 # the * sign multiplies the numbers
30
>>> 6 / 5 # the / sign divides the numbers
1.2
>>> 6 // 5 # the // sign makes an integer division
1
>>> 6 % 5 # the % calculates the modulo
1
>>> 6 ** 5 # the ** sign raises the first number to the power of the second
7776

Comparison operators

These operators compare the values (of variables or the values itself does not matter again). The result is from type Boolean and can be True or False.

>>> 5 == 4 # == is the equality operator, returns True when both sides are equal
False
>>> 4 == 4
True
>>> 5 != 5 # != is the inequality operator, returns False when both sides are equal
False
>>> 5 > 5 # > is the greater than operator
False
>>> 5 < 5 # < is the less than operator False >>> 5 >= 5 # >= is the greater or equal operator
True
>>> 5 <= 5 # <= is the less or equal operator
True

Assignment operators

We already know one of the assignment operators in Python, the equal sign (=). However there are quite some of these operators which have different usages but all of them reduce some code required to write.

In the following example I will use the same variable over and over again to show how these operators work. Again, if you find yourself wondering about what the examples mean, feel free to write me a mail and I will add a description to those examples.

You can see the value of the variable in the interactive interpreter when you enter just the name of the variable (in this case a) and hit return.

>>> a = 5
>>> a += 3 # a has the value of 8
>>> a -= 2 # a has the value of 6
>>> a *= 3 # a has the value of 18
>>> a /= 4 # a has the value of 4.5
>>> a //= 1 # a has the value of 4.0
>>> a %= 6 # a has the value of 4.0
>>> a **= 2 # a has the value of 16.0
>>> a
16.0

Logical operators

There are not much of them: and, or and not. We have encountered them in the easter-eggs already when we have taken a look at what love is. They are logical operators so the best is you have boolean values where you use them.

However there is a little exception of this. 0, empty objects and None are treated as False so you can use them in conditional expressions (which will follow in a later article). Numbers and non-empty objects are treated as True of course.

For now let’s see some examples:

>>> a = True
>>> b = False
>>> a and b
False
>>> a or b
True
>>> not a
False
>>> not b
True
>>> not 0
True
>>> not 1
False
>>> not [] # this is an empty list
True

Membership operator

It comes in handy when we want to see if something is a member of a collection. For example the number 4 is in the list of the first 5 prime numbers.

The membership operator is the in keyword. Some books add not in to this list too but as far we have learned not is a logical operator which negates the value used on.

The result is a boolean True or False.

>>> primes = [2,3,5,7,11]
>>> 4 in primes
False
>>> 4 not in primes
True
>>> 5 in primes
True
GHajba
 

Senior developer, consultant, author, mentor, apprentice. I love to share my knowledge and insights what I achieve through my daily work which is not trivial -- at least not for me.

Click Here to Leave a Comment Below 0 comments