Basic data types in Python

Python Data Types – Complete Tutorial

The purpose of any computer program is to store and process some data. To store and get easy access to the data in the Python program, we need to use variables. Each variable in Python is an object. Also, Python provides us with several essential data types, which allow us to process strings, numbers, boolean values, and many others. In this chapter, we’ll cover Python variables and their basic data types.

Variables in Python

As we already mentioned in the intro section, variables are used in Python to store and provide easily named access to some information or data.

Defining a variable in Python

To define a variable, you need to specify the variable name and assign it a value using the = operator.

Here are some examples of variables in Python:

s3_bucket_name = 'hands-on-cloud-python-course-src-bucket'
s3_bucket_files_count = 1
s3_bucket_public_accessible = False
s3_bucket_files = ['example_image.png']

Getting variable type in Python

Python is smart enough to understand the variable data type based on provided value.

To get a variable type, you can use a special built-in type() Python function.

Here’s an example of type() function call for s3_bucket_name variable:

print(type(s3_bucket_name))

This means that the variable type is a string.

Check types of other variables yourself.

You should get the following results.

1. Variables and basic data types in Python - Getting variable type

Reassigning variables in Python

You can reassign Python variable values at any moment of program execution, regardless of the variable data type.

The new variable data type will be the type of a new variable, for example:

my_variable = 'Some text'
my_variable = 777

The new data type for my_variable will be:

print(type(my_variable))

Here’s an expected result:

2. Variables and basic data types in Python - Reassigning variable type

Deleting variables in Python

Sometimes it might be required to delete variables during your program execution completely.

You can accomplish this by using del statement:

my_variable = 'Some text data'
del my_variable

Now, if you try to access my_variable the variable, you’ll get the following error message:

Traceback (most recent call last):
   File "", line 1, in 
 NameError: name 'my_variable' is not defined

Now, as soon as we learn how to use Python variables, let’s review their basic data types.

Case sensitivity in Python

Python is case sensitive programming language.

That means that variables EC2_instance_id and ec2_instance_id are not the same and will store different data:

EC2_instance_id = 'i-0e9a442e6332682dc'
ec2_instance_id = 'i-0f9c549c677c682ed'
print(EC2_instance_id)
print(ec2_instance_id)

Python data types

Python supports various data types that allow us to store and process strings, various types of numbers, results of logical operations, and more complex types of data like lists (arrays), sets, dictionaries, tuples, dates, times, and many more.

Let’s review them one by one.

Boolean

The boolean type is needed to store the results of logical operations in Python.

Variable of the boolean type can have only one of two possible values:

  • True
  • False

Here’s an example:

is_ec2_instance_stopped = True
print(is_ec2_instance_stopped)
print(type(is_ec2_instance_stopped))

Interpreter output at Cloud9 IDE:

3. Variables and basic data types in Python - Boolean variable

Numbers

There are three types available in Python to represent numeric values:

  • int
  • float
  • complex

There is effectively no limit to how long an integer value can be in Python; the only constraint is the amount of memory on your system.

Decimal numbers

A sequence of digits without any prefix can be interpreted as a decimal number.

For example:

number = 123456789012345678901234567890
print(number)
print(type(number))

Interpreter output at Cloud9 IDE:

4. Variables and basic data types in Python - Decimal Integers

If you need to use a value with a base other than 10, you need to use the following prefixes:

  • 0x – represents hexadecimal values with base equals 16, for example: 0x313377
  • 0o – represents for octal values with base equals 8, example: 0o50461
  • 0b – used for binary values with base equals 2, for example: 0b11101
a = 0x313377
print(a)
print(type(a))
b = 0o50461
print(print(b))
print(type(b))
c = 0b11101
print(c)
print(type(c))

Interpreter output at Cloud9 IDE:

5. Variables and basic data types in Python - Hexadecimal, octal and binary integers

Floating-point numbers

Floating-point numbers in Python represented via float type.

To declare a float value, you need to use the point as a part of the decimal number.

Optionally, you can use the e character followed by a positive or negative integer to specify an E scientific notation of the value.

For example:

a = 5.5
print(a)
print(type(a))
b = .5
print(b)
print(type(b))
c = 5.
print(c)
print(type(c))

Interpreter output at Cloud9 IDE:

6. Variables and basic data types in Python - Floating-point numbers

Complex numbers

Complex numbers are not important for our course, so we’ll provide the syntax to specify them only:

a = 2+1j
print(a)
print(type(a))

Strings

In Python, strings are represented via str type.

You can define string values using single and double; multi-line strings are defined using triple-quoted syntax.

The string may contain a virtually unlimited amount of characters; the only limit is your system’s memory.

This is one of the most important data types because you’ll be dealing with strings a lot during your career as Cloud Engineer. Some of the most common examples are:

String in single quotes ( ' )

One way to set up a string value to the variable in Python is to define it using single ( ' ) quotes:

my_string = 'this is my string'
print(my_string)

Interpreter output at Cloud9 IDE:

7. Variables and basic data types in Python - Strings - Single quoted

Strings in double quotes ( " )

Another way to define string is to put a character sequence in double-quotes ( " ):

my_string = "this is my string"
print(my_string)

Interpreter output at Cloud9 IDE:

8. Variables and basic data types in Python - Strings - Double quoted

Quotation marks within quotation marks

Sometimes, your string variable text might contain quotes.

Keep in mind that if a string is defined using single ( ' ) quotes, you can’t directly specify a single quote character as part of your string text; that will lead to an interpreter error:

my_string = 'It's a great course'
   File "", line 1
     my_string = 'It's a great course'
                    ^
 SyntaxError: invalid syntax

To be able to specify your string, you need to use either use double quotes for a string value:

my_string = "It's a great course"

Or you can use the “escape” single quote using backslash ( \ ) symbol:

my_string = 'It\'s a great course'

You need to use the same approach for dealing with strings in double quotes.

9. Variables and basic data types in Python - Strings - Mixing and escaping quotes

String in triple quotes ( ''' and """ )

Another way to specify a string value is to provide its value in triple single ( ''' ) or triple-double ( """ ) quotes.

Such an approach provides you with some benefits:

  • The such syntax allows you to specify a multi-line string
  • You do not have to escape quotes

Here are some examples of defining strings in triple quotes:

my_string = '''It's a great course'''
print(my_string)

my_string = """this is first line of the string
this is the second line of the string"""
print(my_string)

Interpreter output at Cloud9 IDE:

10. Variables and basic data types in Python - Strings - Multi-line strings

In your Python code, strings that are specified using triple single ( ''' ) or triple-double ( """ ) quotes syntax and are not assigned to variables interpreted as multi-line comments.

!/usr/bin/env python3
"""
This is simple "Hello World" example
"""
print("Hello AWS World")

Interpreter output at Cloud9 IDE:

11. Variables and basic data types in Python - Strings - Multi-line strings (comments)

List

A list (or an array) in Python is a data structure to contain ordered items (usually of the same type, but it is not required).

It’s an immutable data structure, which means you can change a list after it has been created by adding and removing items or even changing item’s values.

We’ll cover the most important operations for Python lists in the next chapter; as for now, here’s an example of its declaration:

ec2_instance_amis = [
    'ami-077e31c4939f6a2f3',
    'ami-00399ec92321828f5',
    'ami-086850e3dda52e84a'
]
print(ec2_instance_amis)
print(type(ec2_instance_amis))

Interpreter output at Cloud9 IDE:

12. Variables and basic data types in Python - List example

Tuples

In Python, a tuple is a data structure that is identical to a list except for the following features:

  • Tuples are defined by using parenthesis ( ) instead of square brackets [ ].
  • Tuples are immutable – you can not change a tuple after defining it.

Here is an example of a tuple:

ec2_instance_amis = (
    'ami-077e31c4939f6a2f3',
    'ami-00399ec92321828f5',
    'ami-086850e3dda52e84a'
)
print(ec2_instance_amis)
print(type(ec2_instance_amis))

Interpreter output at Cloud9 IDE:

13. Variables and basic data types in Python - Tuple example

Sets

Another interesting and useful data type in Python is sets.

A set is an unordered collection of items with no duplicate elements.

Sets are handy when you need to solve the following problems:

  • Find common items between two or more lists
  • Find what items in one list do not belong to another
  • Quickly remove duplicates from the list

Here’s an example of a set declaration:

ec2_instance_tag_keys = {
    'Name',
    'Department',
    'CostCenter'
}
print(ec2_instance_tag_keys)
print(type(ec2_instance_tag_keys))

Interpreter output at Cloud9 IDE:

14. Variables and basic data types in Python - Set example

Dictionaries

Dictionary in Python is a data structure consisting of key-value pairs, with the requirement that the keys are unique within a dictionary.

Such a structure allows you to get quick access to a dictionary item by its key.

This data structure is commonly used to store JSON-formatted data.

Here’s an example:

ec2_instance_tags = {
    'Name': 'dev-host',
    'Department': 'IT',
    'CostCenter': 54321
}
print(ec2_instance_tags)
print(type(ec2_instance_tags))

Interpreter output at Cloud9 IDE:

15. Variables and basic data types in Python - Dict example

Typecasting

Typecasting allows you to convert data of one data type to another.

The most common examples are:

  • Convert int into a str.
  • Convert float into an int.

Explicit typecasting

We’re doing explicit typecasting when we need to specify the target data type ourselves.

String

To cast a variable to a str type, use the str() function:

# int to str typecasting
my_string = str(313377)
print(my_string)
print(type(my_string))
# float to str typecasting
my_string = str(35.435)
print(my_string)
print(type(my_string))

Interpreter output at Cloud9 IDE:

16. Variables and basic data types in Python - Typecasting to string

Integer

To cast the variable to int type, you need to use int() function:

# str to int typecasting
my_integer = int('313377')
print(my_integer)
print(type(my_integer))
# float to int typecasting
my_integer = int(35.435)
print(my_integer)
print(type(my_integer))

Interpreter output at Cloud9 IDE:

17. Variables and basic data types in Python - Typecasting to integer

Please, pay attention that if your str data can not be cast to int type, you’ll get the following error:

my_integer = int('seven')
 Traceback (most recent call last):
   File "", line 1, in 
 ValueError: invalid literal for int() with base 10: 'seven'

Float

Similar to previous examples, to cast the variable to float type, use float() function:

# str to int typecasting
my_float = float('313377')
print(my_float)
print(type(my_float))
# int to float to int typecasting
my_float = float(313377)
print(my_float)
print(type(my_float))

Interpreter output at Cloud9 IDE:

18. Variables and basic data types in Python - Typecasting to float

Please, pay attention that if your str data can not be cast to float type, you’ll get the following error:

my_float = float('seven point zero')
 Traceback (most recent call last):
   File "", line 1, in 
 ValueError: could not convert string to float: 'seven point zero'

Implicit typecasting

The implicit typecasting happens when, for example, you’re summing an int and a float variables:

my_integer = 313377
my_float = 313377.0
my_sum = my_integer + my_float
print(my_sum)
print(type(my_sum))

Python has been able to identify that both variables are of numeric type and allowed us to save a result of the sum operation to my_sum variable of type float.

The type of my_sum variable is float, because Python protects us from data loss, as the int type can not contain floating-point data.

You should not expect that Python will always be able to do implicit typecasting.

For example, we can not add int or float variable to string without explicit type casting:

my_integer = 313377
my_string = 'The number is: '
result = my_string + my_integer
Traceback (most recent call last):
   File "", line 1, in 
 TypeError: can only concatenate str (not "int") to str

To fix this problem, you have to cast int type to string:

result = my_string + str(my_integer)
print(result)
print(type(result))

Interpreter output at Cloud9 IDE:

19. Variables and basic data types in Python - Implicit typecasting examples

Similar Posts