Basic types

In this section we go through the built-in basic types offered by Python: int, float, bool, NoneType and str.


The most basic numerical type is the integer. Python considers any number without a decimal point to be of type int:

>>> n = 6
>>> type(n)
<class 'int'>

Integers support the usual arithmetic operations + (sum), - (substraction), * (product), // (integer division), % (remainder of division), ** (power) and they can be compared with relational operators (==, !=, <, <=, >, >=):

>>> 22 // 7
>>> 22 / 7          # By default, division casts to floating-point type

One remarkable feature is that integers are of variable precision and there is no need to worry about overflow issues:

>>> 2 ** 100

Floating-point numbers

The float type represents real numbers and they can be defined either in standard decimal notation or in exponential notation:

>>> n = 1.23
>>> G = 6.67408e-11

They support the same arithmetic and relational operators as integers, exchanging the integer division // by the real division /.


The boolean type has two possible values: True and False. Relational operators such as ==, !=, <, <=, >, >= return booleans and they can be operated by means of and (conjunction), or (disjunction) and not (negation).

None Type

Python offers one special value None of type NoneType that is frequently used to represent the absence of a value.


In Python you can explicitly convert different types using the desired name of the type as if it were a function. For instance, to convert into integers:

>>> int(6.66)
>>> int(9.99)
>>> int('23')
>>> int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'

Or to convert into floats:

>>> float(12)
>>> float('12')
>>> float('12.24')

Most values can be converted into strings using the str() function:

>>> str(33)
>>> str(3.1416)
>>> str(False)
>>> str([1, 'one', []])
"[1, 'one', []]"


Strings in Python are of type str and consist in sequences of Unicode characters (an standard for the representation of text). Values in strings are immutable: they cannot be modified once they are created. All you can do is create new strings from them.

Note that the character type does not exist in Python.


Strings are created with single or double quotes:

You can also have multiline strings using three quotation marks:

html = """
            <title>My title</</title>
                Some text

Functions for length, minimum and maximum

The len() function returns the number of characters in a string:

>>> len('Everest')
>>> len('A')

The min() and max() functions return the smallest and largest character in a string respectively.

>>> min('Everest')
>>> max('Everest')


These are some of the operators that can be applied to strings:

For instance:

>>> 'Julius' + ' ' + 'Caesar'
'Julius Caesar'
>>> 'spam' * 5
>>> 'flame' in 'the flame that burns twice as bright burns half as long'
>>> 'c' < 'python'


In order to iterate all the characters in a string, a for loop is used:

def number_of_as(text):
    n = 0
    for c in text:
        if c == "A":
            n += 1
    return n

More insight on for loops is given in the Control flow section.


You can create a substring using the indexing operator [], starting from 0:

>>> 'snowing'[0]
>>> 'snowing'[3]
>>> 'snowing'[7]
IndexError: string index out of range

Elements at the end can be accessed using a negative index, starting from -1:

>>> 'snowing'[-1]
>>> 'snowing'[-7]
>>> 'snowing'[-8]
IndexError: string index out of range

In order to extract the substring between two positions you can use the syntax s[start:stop]. Note that stopping point is never part of the generated substring:

>>> 'snowing'[0:4]
>>> 'snowing'[1:4]
>>> 'snowing'[3:4]
>>> 'snowing'[4:4]

In case start is not given it means “from the beginning”. Similarly, if stop is not given it means “until the end”:

>>> 'snowing'[:4]
>>> 'snowing'[4:]

You can also specify a step by means of s[start:stop:step]:

>>> 'snowing'[0:5:2]
>>> 'snowing'[::2]  # Equivalent to l[0:len(l):2]
>>> 'snowing'[::-1]

As we highlighted before, strings are immutable and their characters cannot be modified:

>>> s = 'snowing'
>>> s[0] = 'k'
TypeError: 'str' object does not support item assignment

In order to obtain 'knowing' you can do something like

>>> s = 'k' + s[1:]
>>> s


Strings are objects with many available methods. Here are a few of them:

For a complete outlook of all the available methods refer to the Python documentation or type

>>> help(str)

Substitutions and format

The format() method enables replacements and variable formatting inside a string. Check the documentation about formatting in Python for much more information details (including the new fstrings in Python ≥3.6).

This simple example shows how to apply substitutions in a string:

>>> '{} is {}m high'.format('Mount Everest', 8848)
'Mount Everest is 8848m high'

In case you want to format a floating point number you can specify additional options:

>>> "{}".format(3.65)
>>> "{:.10f}".format(3.65)      # Adds 10 digits after the decimal point
"{:7.3f}".format(3.65)          # Uses 7 characters, 3 of which are after the decimal point
'  3.650'

Víctor Adell
Universitat Politècnica de Catalunya, 2023

Prohibit copiar. Tots els drets reservats.
No copy allowed. All rights reserved.