Variables and basic data types in Python

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

Variables

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

Defining variable

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

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:

>> type(s3_bucket_name)
<class 'str'>

What 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 variable

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

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:

>> type(my_variable)
<class 'int'>

Here’s an expected result:

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

Deleting variables

Sometimes it might be required to delete variable 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 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 learnt how to use variables in Python, let’s review their basic data types.

Case sensitivity

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)
i-0e9a442e6332682dc
>> print(ec2_instance_id)
i-0f9c549c677c682ed

Python basic 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, date, time and many more.

Let’s review them one by one.

Boolean

The boolean type is needed to store results of logical operations 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)
True
>> type(is_ec2_instance_stopped)
<class 'bool'>

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 constrained is the amount of memory on your system.

Decimal numbers

A sequence digits without any prefix is to be interpreted as a decimal number.

For example:

>> number = 123456789012345678901234567890
>> print(number)
123456789012345678901234567890
>> type(number)
<class 'int'>

Interpreter output at Cloud9 IDE:

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

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

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

>> b = 0o50461
>> print(b)
20785
>> type(b)
<class 'int'>

>> c = 0b11101
>> print(c)
>> type(c)
<class 'int'>

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 point as a part of the decimal number.

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

For example:

>> a = 5.5
>> print(a)
5.5
>> type(a)
<class 'float'>

>> b = .5
>> print(b)
0.5
>> type(b)
<class 'float'>

>> c = 5.
>> print(c)
5.0
>> type(c)
<class 'float'>

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)
(2+1j)
>> type(a)
<class 'complex'>

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.

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

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

  • Reading and writing objects to S3 buckets
  • Working with EC2 instances Tags
  • Changing with DynamoDB item attributes
  • Doing data transformations using Lambda

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)
this is 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)
this is 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 “escape” single quote using back slash ( \ ) 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 a triple single ( ''' ) or triple double ( """ ) quotes.

Such approach provides you some benefits:

  • 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)
It's a great course

>> my_string = """this is first line of the string
this is the second line of the string"""
>> print(my_string)
this is first line of the string
this is the second line of the 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, what 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)
['ami-077e31c4939f6a2f3', 'ami-00399ec92321828f5', 'ami-086850e3dda52e84a']
>> type(ec2_instance_amis)
<class 'list'>

Interpreter output at Cloud9 IDE:

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

Tuples

In Python, tuple is a data structure that is identical to list, except of 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)
('ami-077e31c4939f6a2f3', 'ami-00399ec92321828f5', 'ami-086850e3dda52e84a')
>> type(ec2_instance_amis)
<class 'tuple'>

Interpreter output at Cloud9 IDE:

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

Sets

Another interesting and very useful data type in Python is sets.

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

Sets are very useful, when you need to solve the following problems:

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

Here’s an example of set declaration:

>> ec2_instance_tag_keys = {
    'Name',
    'Department',
    'CostCenter'
}
>> print(ec2_instance_tag_keys)
{'Name', 'CostCenter', 'Department'}
>> type(ec2_instance_tag_keys)
<class 'set'>

Interpreter output at Cloud9 IDE:

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

Dictionaries

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

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

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

Here’s an example:

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

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)
313377
>> type(my_string)
<class 'str'>

# float to str typecasting
>> my_string = str(35.435)
>> print(my_string)
35.435
>> type(my_string)
<class 'str'>

Interpreter output at Cloud9 IDE:

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

Integer

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

# str to int typecasting
>> my_integer = int('313377')
>> print(my_integer)
313377
>> type(my_integer)
<class 'int'>

# float to int typecasting
>> my_integer = int(35.435)
>> print(my_integer)
35
>> type(my_integer)
<class 'int'>

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 casted 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 variable to float type, use float() function:

# str to int typecasting
>> my_float = float('313377')
>> print(my_float)
313377.0
>> type(my_float)
<class 'float'>

# int to float to int typecasting
>> my_float = float(313377)
>> print(my_float)
313377.0
>> type(my_float)
<class '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 casted 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 is happening 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)
626754.0
>> type(my_sum)
<class 'float'>

Python has been able to identify, that both variables are of numeric type and allowed us to save a result of 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)
The number is: 313377
>> type(result)
<class 'str'>

Interpreter output at Cloud9 IDE:

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

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment