Python Guide #3: Variables and Datatypes
Since you already know, how to create Python program and execute it, it is time to learn about variables and datatypes.
What is a variable?
You can imagine variable as a container that stores some kind of data, referred as value. Variables are referenced to by their name.
Declaring variables in Python
You create a variable, by assigning value to it. In Python, you don’t have to declare the type of data you want to store in the variable. Programming languages, that do not need datatype to be specified, are called dynamically typed languages, while languages, that need to have data type specified, are called statically typed languages.
Slight disadvantage of dynamically typed languages, is that they are slower than statically typed. However, with the speed of modern computers, convenience of dynamically typed language beats the need to perform fast.
To go through this quick guide, create Python file vars.py
(preferably in the same folder you used in previous guide, but it is really up to you) and open it.
# to create a variable
# type name, that you want
# your variable to be called
# followed by equal sign and value
a = 10
b = 5
# Now lets print these variables,
# as in previous guide
print(a)
print(b)
Output will look like this:
10
5
As you can see declaring variables in python is easy. You can also change variables value, by assigning new value to it.
a = 10
a = 5
# Value of variable "a" will change from 10 to 5
Now we can upgrade our “Hello World!” program, to use variables, as show below.
message = "Hello World!"
print(message)
The output will be exactly same, as from “Hello World!” program:
Hello World!
Python datatypes
Datatype, known as shortly type, tells compiler or interpreter how you intend to use your data.
To print type of data use function type()
, try it for yourself.
x = 20
print(type(x))
Text Type
In Python, there is one text variable, a string
. Strings can be presented in different ways. String is referred in Python str
# You can use " symbol
string_1 = "Example text, double qoutes"
# As well as ' symbol
string_2 = 'Example text, single quotes'
# This is a special case, where
# the string spans across multiple lines.
string_3 = """
This way you declare text
that you intend to be a multiline
text. Using double quotes.
"""
# You can also use single quotes, as
# in the first case
string_4 = '''
This way you declare text
that you intend to be a multiline
text. Using single quotes.
'''
Numeric Types
Numeric data types are numbers, probably most often used types in programming. In next guides I will teach you how to do operations with numbers.
Integer: int
Number, that is whole, written without fraction.
a = 5
# This way, declared variable is an integer
Float: float
Floating point number, that allows to present fractional components. In Python, in place of a coma we use “.”.
a = 1.5
# This way, declared variable is a float
Complex: complex
Used to represent complex numbers. Complex numbers consist of two parts, realis and imaginaris. They are rarely used for practical, everyday tasks. They are used in math and physics. One example where complex numbers come helpful is in calculating alternating current circuits.
a = 2j
# a is a complex number, where
# j is equal to square root of -1
Sequence Types
Sequence types are used to store multiple values, organized and under one variable.
List: list
# List is created, by assigning multiple
# values to one variable, using a square bracket.
vegetables = ["carrot", "potato", "tomato"]
# Lets print first element from the
# list above
# in python first element is 0 element
print(fruits[0])
# Lists can be changed
fruits[0] = "yam"
# after this operation
# list of fruits will look like this
["yam", "potato", "tomato"]
Output
apple
Tuple: tuple
Tuples, as lists, are used to store multiple values under same variable. Unlike a list, tuples can’t be changed. They are declared in same way as a list, but instead of square brackets, round one is used.
fruits = ("carrot", "potato", "tomato")
# To access values within a tuple,
# index is used, as with the list
print(fruits[1])
# Outputs
# carrot
Mapping Type
Dictionary: dict
Dictionary lets you store multiple values, assigned to different keys, under one variable. It works like a real life dictionary, lets use an example to visualize it.
# Below I made a small dictionary
# which has english number names as keys
# and spanish number names as values
to_spanish = {
one: "uno",
two: "dos",
three: "tres"
}
# To access data stored in a dictionary
# You use similar syntax as with a list
# However, instead of index, you provide
# a key
# Lets test it out using print()
print(to_spanish["one"])
print(to_spanish["three"])
Output:
uno
tres
Set: set
Set is, like list and a tuple, object used to store multiple values. It is not ordered and not index, which means, that you can’t access its individual values. Unlike in tuple and list, values stored within a set can’t repeat.
# To declare a set you use curly brackets
set_of_cars = {"volkswagen", "ferrari", "lamborghini"}
Boolean Type: bool
Bool can have one of two values, it is either False
or True
yes = True
no = False
print (yes, no)
Output
True False
Binary Types
Bytes: bytes
Used to store sequences of single bytes. They can’t be modified (immutable)
my_bytes = b"This is how you declare byte object"
Bytearray: bytearray
Bytearray is sequence of integers ranged from 0 to 255, it is mutable, used for working with low level data.
Memory View: memoryview
You can use memoryview to expose inner data of python objects. You won’t need it until much later.
Conclusion
In this guide you learned about variables and datatypes in Python, how to declare them and their basic properties. It is not important right now to memorize it. You will get to know them, by programming and experiencing what dfferent datatypes provide to you and where they suit your needs.