The Python Language 1

Learn basic Python types in this lesson.

We'll cover the following

Comments

In Python, the # symbol is used to indicate a comment:

# This is a Python comment

From this point on, comments will be used to annotate code snippets.

Variables

As mentioned in the previous lesson, Python is a dynamically-typed language. This means that we do not declare the types of variables. There are also no const or var qualifiers; it is not possible to declare a variable as “constant”.

a = 1    # create the variable "a" and assign the value 1
b = 2    # create the variable "b" and assign the value 2
a = b    # assign the value of b to a, a is now 2

Note: in Python, an assignment doesn’t create a copy of the value being assigned, but instead creates a reference to the value. Further information about this can be found here.

Functions

Functions are called by using a function name and matched parentheses with zero or more arguments, familiar from many other languages:

f()        # call the function "f" with zero arguments
f(a, b)    # call the function "f" passing in a and b as arguments

We will explore how to create user-defined functions in lesson 4.

Numeric types

The main numeric types are:

  • int: holding an arbitrary length signed integer
  • float: normally being implemented internally using a C IEEE 754 64-bit double

This differs from C-style languages where integer types have a fixed size (32-bit unsigned, 64-bit, etc).

For example, in Python, we can write:

Press + to interact
x = pow(2, 255) # generate a 256-bit int and assign to x
y = x.bit_length() # display number of bits needed to represent x
print(y)
x = pow(2, 53) # generate a 54-bit int and assign to x
y = x + 1 # add 1 to the int
print(y) # value is 9007199254740993
y = float(y) # convert y to a float
print(y) # value is 9007199254740992.0!

Note: Here we use Python’s pow() function, which raises 2 to the power of 255.

In the above example, float(y) is not an accurate representation of the int value of y. Why is that?

Strings

Strings are immutable sequences of Unicode characters. Python uses UTF-8 encoding by default. The actual type for Python strings is str.

Press + to interact
"Foo" # double quoted string
'Foo' # single quoted string (equivalent)
"Hello 'Foo'" # nested quotes, no need to escape
"""
Multi-line
""" # triple quotes form 'idiomatic' multi-line string
print('Unicode rocks 😎')
print(type('Foo'))

As a sequence type, individual elements in a string can be accessed using a square brace syntax that you will be familiar with from other languages.

Press + to interact
a = 'Foo' # assign 'Foo' to variable a
b = a[0] # assign the zeroth element of a to b
print(b) # b is 'F'
a[1] = 'f' # a is immutable, will throw a TypeError exception

Now try using help() from the previous lesson to learn more about Python strings.