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 integerfloat: normally being implemented internally using a C IEEE 754 64-bitdouble
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:
x = pow(2, 255) # generate a 256-bit int and assign to xy = x.bit_length() # display number of bits needed to represent xprint(y)x = pow(2, 53) # generate a 54-bit int and assign to xy = x + 1 # add 1 to the intprint(y) # value is 9007199254740993y = float(y) # convert y to a floatprint(y) # value is 9007199254740992.0!
Note: Here we use Python’s
pow()function, which raises2to the power of255.
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.
"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 stringprint('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.
a = 'Foo' # assign 'Foo' to variable ab = a[0] # assign the zeroth element of a to bprint(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.