Dr Seán Carroll

by Dr Seán Carroll

Lesson

Python 101 - The (very) Basics

12. Variables and Python data types

Variables


In Python, as well as in other programming languages, variables allow you to store, update, and retrieve values throughout your code. You can think of them as containers or labels for values that you can use and manipulate in your code. You assign a value to a variable using the assignment operator =. The variable name is placed on the left side of the operator, and the value is placed on the right side, for example:

age = 25

In this example, we created a variable called age and assigned it the value 25. Variable names are case-sensitive, so age and Age would be different variables. It's also important to choose descriptive variable names that make your code easier to understand. For example, age is a better variable name than a for representing a person's age.

Using Variables

Once a variable is assigned a value, you can use it in various operations and expressions. For example, you can use variables in mathematical operations, string concatenations, or function arguments.

price = 10
quantity = 5
total = price * quantity
print("Total cost:", total)  # Output: Total cost: 50

In this example, we use the variables price and quantity in a mathematical operation to calculate the total cost.

Updating Variables

You can update the value of a variable by assigning a new value to it. This new value can be based on the variable's previous value or other variables.

counter = 0
counter = counter + 1  # The value of counter is now 1
counter += 1  # This is a shorthand for "counter = counter + 1". The value of counter is now 2.

Python Data Types


Now that you understand the concept of a variable, it's time to dive into the different data types that variables can store. Remember, variables are like containers or labels for values. These values can be of various types, such as numbers, text, or collections of items.

In Python, different data types have distinct properties and uses, which can help you efficiently represent and manipulate information in your programs. Knowing how to choose and work with the appropriate data types is essential for writing clear and efficient code.

In the following sections, we will explore the various data types available in Python, their benefits, typical use cases, and code snippets to demonstrate their usage. This will give you a solid foundation for working with different data types in your Python programs.

Integers (int)

The first data type we’ll consider is integers or ints. We’ve already seen these used in our previous examples. Integers are whole numbers, both positive and negative. They are a fundamental data type in Python and many other programming languages. There are a number of benefits to using ints:

  • Efficiency: Integers are memory-efficient and offer faster calculations compared to other numerical data types like floating-point numbers. This makes them the preferred choice when working with whole numbers.

  • Accuracy: Integers provide exact representations of whole numbers, which eliminates any risk of rounding errors that can occur with floating-point numbers.

  • Versatility: Integers are used in a wide range of applications, from counting and indexing to more complex mathematical operations.

Floats

Floating-point numbers, or floats, are real numbers with a decimal point. They're used to represent fractional values and can handle a wide range of numerical values, including very large and very small numbers. Floats have a number of benefits:

  • Precision: Floats can represent a vast range of real numbers with varying levels of precision, making them suitable for a wide variety of applications that require decimal values or approximation.

  • Range: The float data type can represent very large or very small numbers using scientific notation, allowing you to work with a wide range of numerical values.

When working with floats, keep in mind that they can have some limitations due to the way they're represented in memory. In certain cases, floating-point arithmetic can lead to rounding errors, making some calculations imprecise. For example:

result = 0.1 + 0.2  # The result should be 0.3
print(result) #Actual result: 0.30000000000000004

To handle issues, you can use the round() function or the math.isclose() function to compare floating-point numbers with a certain tolerance. For example,

import math

tolerance = 1e-9

if math.isclose(0.1 + 0.2, 0.3, rel_tol=tolerance):
  print("The result is close to 0.3")

Strings

The next data type we'll consider is a String. This is a sequence of characters enclosed in quotes (single or double). Strings are used to represent and manipulate text in Python (and many other programming languages). In Python, strings are immutable, which means that once a string is created, its content cannot be changed directly. However, you can still perform various operations on strings to create new modified strings. The benefits of strings are:

  • Flexibility: Strings can represent text of any length, from a single character to large blocks of text. They can include letters, numbers, punctuation marks, whitespace characters, and even special characters like emoji.

  • Unicode Support: Python strings use the Unicode standard, which means they can represent characters from virtually all languages and writing systems.

  • Rich Built-in Methods: Python provides a wide range of built-in string functions that allow you to perform various text manipulation tasks, such as searching, replacing, splitting, and formatting.

For example, consider the following string:

text = "Hello World" # This is a string
print(text) # Output: Hello World

#Change the text to upper case
textUpper = text.upper()
print(textUpper) # Output: HELLO WORLD

#Split the string by word into two words
textSplit = text.split()
print(textSplit) # Output: ['Hello', 'World']

We can also create strings dynamically by directly inserting variables into them, for example:

name = "Seán"
template = f"Hello, {name}!"
print(template) # Output: Hello, Seán!

Lists

Lists are our first collection data type. This simply means that they are made up of a collection of other variables. They're a versatile and mutable data type, used to store an ordered sequence of elements. These elements can be of any data type, such as integers, floats, strings, or even other collections like tuples or dictionaries. Lists can also contain elements of mixed data types, making them highly flexible for organising and processing data. Lists have a lot of very helpful features:

  • Dynamic Size: Lists can grow or shrink dynamically as you add or remove elements, providing flexibility when working with varying amounts of data.

  • Mutable: Lists are mutable, which means you can modify their content by adding, removing, or changing elements after the list is created.

  • Versatile: Lists can store elements of any data type, including mixed data types, allowing you to create complex data structures.

  • Built-in Functions and Methods: Python provides a rich set of built-in functions and methods for working with lists, making it easy to perform operations like sorting, searching, or filtering.

We can define a list of strings as follows:

# Defining a list
names = ["Alice", "Bob", "Charlie"]
print(names) # Output: ['Alice', 'Bob', 'Charlie']

#Append a new name to the list
names.append("David")
print(names) # Output: ['Alice', 'Bob', 'Charlie', 'David']

#Removing the first element of the list
names.pop(0)
print(names) # Output: ['Bob', 'Charlie', 'David']

#Accessing the second element of the list
print(names[1]) # Output: Charlie

We also have methods that are particularly helpful with lists containing ints and floats. Let's consider a couple of examples.

numbers = [5, 2, 8, 1, 3]
print(numbers)

# Sorting the list
numbers.sort()  # Output: [1, 2, 3, 5, 8]
print(numbers)

# Reversing the list
numbers.reverse()  # Output: [8, 5, 3, 2, 1]
print(numbers)

length = len(numbers)  # Output: 5
print(length)

maximum = max(numbers)  # Output: 8
print(maximum)

minimum = min(numbers)  # Output: 1
print(minimum)

Tuples

The next data type we’ll consider is Tuples. Tuples are very similar to lists in that they are another collection data type. However, tuples are immutable. They’re used to store an ordered sequence of elements. Similar to lists, tuples can hold elements of any data type, including mixed data types.

However, unlike lists, tuples are immutable, meaning that once a tuple is created, its content cannot be changed directly. This immutability makes tuples suitable for representing fixed collections of data, where modification is not required. Their benefits include:

  • Immutability: because tuples are immutable, their content remains constant throughout the lifetime of the tuple. This property can be beneficial in certain scenarios where data integrity is crucial.

  • Versatility: tuples can store elements of any data type, including mixed data types, allowing you to create complex data structures.

While lists and tuples both store ordered sequences of elements, the choice between the two depends on your specific use case. If you need a mutable, dynamic data structure, a list is the appropriate choice. On the other hand, if you require an immutable, memory-efficient data structure, a tuple is the better option.

Tuples have many of the same built-in functions as lists. Let's consider some examples.

numbers = (5, 2, 8, 1, 3)
print(numbers)

length = len(numbers)  # Output: 5
print(length)

maximum = max(numbers)  # Output: 8
print(maximum)

minimum = min(numbers)  # Output: 1
print(minimum)

fruits = ("apple", "banana", "cherry", "apple")

apple_index = fruits.index("apple")  # Output: 0
print(apple_index)

apple_count = fruits.count("apple")  # Output: 2
print(apple_count)

Dictionaries

Dictionaries are the final data type we'll explore here. Dictionaries are a powerful and flexible collection data type. They're used to store unordered collections of key-value pairs. Keys in a dictionary are unique, while values can be of any data type, including other collections like lists or other dictionaries. Dictionaries are mutable, allowing you to add, remove, or modify key-value pairs after the dictionary is created.

Dictionaries have the following benefits:

  • Efficient Lookup: Dictionaries provide fast and efficient access to values based on their keys, making them ideal for situations where quick lookups are required.

  • Flexible: Dictionaries can store values of any data type, including mixed data types, allowing you to create complex data structures.

  • Dynamic: Dictionaries can grow or shrink dynamically as you add or remove key-value pairs, offering flexibility when working with varying amounts of data.

  • Readable: Dictionaries provide a clear and concise way to represent data, making it easy to understand the structure and relationships among data elements.

The core feature of dictionaries is their ability to store associations between keys and values. This allows you to quickly look up values based on their associated keys. For example, consider the following dictionary that stores details of a particular person or user:

user = {'name': 'John', 'age': 25, 'hobbies': ['Playing Music', 'Watching Movies']}
print(user) # Output: {'name': 'John', 'age': 25, 'hobbies': ['Playing Music', 'Watching Movies']}

We can access the value associated with a key using the following syntax:

print(user['name']) # Output: John

We can also add new key-value pairs to a dictionary:

user['email'] = 'john@test.com'
print(user) # Output {'name': 'John', 'age': 25, 'hobbies': ['Playing Music', 'Watching Movies'], 'email': 'john@test.com'}

Similarly, we can use del and pop to remove key-value pairs from a dictionary:

del user['age']
print(user) #Output: {'name': 'John', 'hobbies': ['Playing Music', 'Watching Movies'], 'email': 'john@test.com'}

removedHobbies = user.pop('hobbies') #Pop returns the value of the key that was removed
print(removedHobbies) # Output: ['Playing Music', 'Watching Movies']
print(user) # Output: {'name': 'John', 'email': 'john@test.com'}

We can also use the update() method to add multiple key-value pairs to a dictionary:

user.update({'name': 'Dave', 'age': 32, 'email': 'dave@test.com'})
print(user) # Output: {'name': 'Dave', 'email': 'dave@test.com', 'age': 32}

Finally, we can use the clear() method to remove all key-value pairs from a dictionary:

user.clear()
print(user) # Output: {}

This is all we need to cover on variables and basic data types. Everything else we'll pick up along the way. In the next we'll introduce another fundamental building block - functions.