Language basics ↩
- The look’n’feel of Python
- The print statement
- Comments
- The None object
- The boolean object
- Object types
- Error messages
Now that we know where to write Python code, let’s have a look at the Python language.
The look’n’feel of Python
Python is meant to be an easily readable language. Its formatting is visually uncluttered, and it often uses English keywords where other languages use punctuation.
Unlike many other languages, Python uses indentation instead of using braces for grouping statements. In Python, whitespace is not optional. This gives Python a characteristic clean, organized structure.
Instead of writing statements in C like this:
if (a < b) {
mmax = b;
} else {
mmax = a;
}
Python dispenses braces altogether, along with the trailing semicolons:
if a < b:
mmax = b
else:
mmax = a
The print statement
The command print
simply ‘prints’ the given argument in the console or output window.
This is all you need to write you first Python program, the famous ‘hello world’:
print('hello world')
The
Comments
Comments are parts of your code that are not executed. They usually contain notes for your future self or for any other programmers reading the code. Comments can also be used to turn certain parts of code on/off during development.
Comments are marked by a #
sign. Everything after the #
is a comment and is not executed:
# my first program!
print('hello world')
A comment can also appear in the middle of a line:
print('hello world') # hi there, I'm a comment
The None object
Most programming languages have a special object type to represent nothing, emptyness. In Python, this is the None
object:
a = None
Note that this is different from 0
, or an empty string ''
, or an empty list []
. None
is the absence of a value of any type.
The boolean object
The bool
object is a special object which can have only two values, True
or False
. Booleans represent a binary state:
>>> a = True
>>> type(a)
<type 'bool'>
>>> b = False
>>> type(b)
<type 'bool'>
In Python, boolean values are always written with a capital first letter, so true
or false
will throw an error:
>>> a = false
Traceback (most recent call last):
File "<untitled>", line 1, in <module>
NameError: name 'false' is not defined
Object types
There are several different object types in Python. Here are the main ones:
str
stringsint
integersfloat
floating point numberslist
liststuple
tuplesdict
dictionariesbool
booleans- etc.
Each type of object has its own properties and methods. Strings are used to represent sequences of characters, integers represent real numbers, lists represent ordered collections of items etc. We’ll be taking a closer look at the main object types in Python in the next sections.
The built-in function type()
returns the type of a given object:
>>> type(None)
<type 'NoneType'>
>>> type('hello')
<type 'str'>
>>> type(123)
<type 'int'>
>>> type(10.5)
<type 'float'>
>>> type({'key':'value'})
<type 'dict'>
>>> type(True)
<type 'bool'>
Error messages
In Python, error messages are objects too – Exception objects. There are various kinds of exceptions, each one for a different situation. When an exception message appears, read it carefully: it usually contains information that will help you to understand and solve the problem.
Here are a few examples of exceptions. Don’t worry if you don’t understand them yet, just try to familiarize yourself with the different kinds of errors:
NameError
-
Happens if we try to use a variable which has not been defined yet:
>>> b
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined
ZeroDivisionError
-
Happens if we try to divide any number by zero:
>>> 1 / 0
Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
IndexError
-
Happens when we try to access an item by an index bigger than the length of the collection:
>>> L = '' >>> L[1]
Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
KeyError
-
Happens if we try to access a non-existing key from a dictionary:
>>> D = {} >>> D['key']
Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'key'
IndentationError
-
Happens when Python is expecting an indented block and doesn’t find one:
>>> for i in range(7): >>> i
Traceback (most recent call last): File "<stdin>", line 2 i ^ IndentationError: expected an indented block
And a few other ones:
TypeError
AssertionError
ImportError
SyntaxError