Python: A Guide to Variables

enghaon

≀Paulo Portela

Posted on February 15, 2024

Python: A Guide to Variables

Introduction

In this chapter, we'll cover how to use different types of variables in Python. In Python, a variable is a named location in memory that stores a value. The value stored in a variable can be of different types, including strings, booleans, integers, floats, complex numbers, tuples, sets, lists, and dictionaries.

Types of Variables

Here are some examples of how to use different types of variables in Python:

# String variable
mathematician = "Euclid"
print(mathematician)
Enter fullscreen mode Exit fullscreen mode
Output:
Euclid
Enter fullscreen mode Exit fullscreen mode
# Boolean variable
is_prime = True
print(is_prime)
Enter fullscreen mode Exit fullscreen mode
Output:
True
Enter fullscreen mode Exit fullscreen mode
# Integer variable
perfect_number = 6
print(perfect_number)
Enter fullscreen mode Exit fullscreen mode
Output:
6
Enter fullscreen mode Exit fullscreen mode
# Float variable
pi = 3.14159
print(pi)
Enter fullscreen mode Exit fullscreen mode
Output:
3.14159
Enter fullscreen mode Exit fullscreen mode
# Complex variable
c = 3 + 4j
print(c)
Enter fullscreen mode Exit fullscreen mode
Output:
(3+4j)
Enter fullscreen mode Exit fullscreen mode
# Tuple variable
dimensions = (3, 4, 5)
print(dimensions)
Enter fullscreen mode Exit fullscreen mode
Output:
(3, 4, 5)
Enter fullscreen mode Exit fullscreen mode
# Set variable
primes = {2, 3, 5, 7}
print(primes)
Enter fullscreen mode Exit fullscreen mode
Output:
{2, 3, 5, 7}
Enter fullscreen mode Exit fullscreen mode
# List variable
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13]
print(fibonacci)
Enter fullscreen mode Exit fullscreen mode
Output:
[0, 1, 1, 2, 3, 5, 8, 13]
Enter fullscreen mode Exit fullscreen mode
# Dictionary variable
math_constants = {"pi": 3.14159, "e": 2.71828, "phi": 1.61803}
print(math_constants)
Enter fullscreen mode Exit fullscreen mode
Output:
{'pi': 3.14159, 'e': 2.71828, 'phi': 1.61803}
Enter fullscreen mode Exit fullscreen mode

In this example, we create variables of different types and assign values to them. We then use the print() function to output the values of the variables to the screen.

Now, let's take a closer look at each of the different types of variables:

  • String: A string is a sequence of characters, used to represent text. In Python, strings are enclosed in quotation marks, either single quotes (') or double quotes ("). In the example above, we create a string variable mathematician and assign the value "Euclid" to it.

  • Boolean: A boolean is a data type that can have one of two values: True or False. Booleans are often used to represent the truth value of a condition or expression. In the example above, we create a boolean variable is_prime and assign the value True to it.

  • Integer: An integer is a whole number, without a fractional component. In Python, integers are represented using the int data type. In the example above, we create an integer variable perfect_number and assign the value 6 to it.

  • Float: A float is a number with a decimal point, used to represent real numbers. In Python, floats are represented using the float data type. In the example above, we create a float variable pi and assign the value 3.14159 to it.

  • Complex: A complex number is a number that can be expressed in the form a + bj, where a and b are real numbers and j represents the square root of -1. In Python, complex numbers are represented using the complex data type. In the example above, we create a complex variable c and assign the value 3 + 4j to it.

  • Tuple: A tuple is an ordered, immutable collection of elements. In Python, tuples are enclosed in parentheses (( and )), with the elements separated by commas. In the example above, we create a tuple variable dimensions and assign the value (3, 4, 5) to it.

  • Set: A set is an unordered collection of unique elements. In Python, sets are enclosed in curly braces ({ and }), with the elements separated by commas. In the example above, we create a set variable primes and assign the value {2, 3, 5, 7} to it.

  • List: A list is an ordered, mutable collection of elements. In Python, lists are enclosed in square brackets ([ and ]), with the elements separated by commas. In the example above, we create a list variable fibonacci and assign the value [0, 1, 1, 2, 3, 5, 8, 13] to it.

  • Dictionary: A dictionary is an unordered collection of key-value pairs. In Python, dictionaries are enclosed in curly braces ({ and }), with the key-value pairs separated by commas and the key and value separated by a colon (:). In the example above, we create a dictionary variable math_constants and assign the value {"pi": 3.14159, "e": 2.71828, "phi": 1.61803} to it.

Type Checking

To get the type of a variable in Python, you can use the type() function. Here's an example of how to use the type() function to get the type of a variable:

x = 5
print(type(x))
Enter fullscreen mode Exit fullscreen mode
Output:
<class 'int'>
Enter fullscreen mode Exit fullscreen mode

In this example, we create a variable x and assign the value 5 to it. We then use the type() function to get the type of the variable x, which is int, and output it to the screen using the print() function.

Deleting Variables

In Python, we can delete a variable using the del keyword. This removes the variable and its value from the current namespace, freeing up the memory used by the variable. For example, to delete a variable named x, we can use the following code:

x = 10
print(x)
Enter fullscreen mode Exit fullscreen mode
Output:
10
Enter fullscreen mode Exit fullscreen mode
del x
print(x)
Enter fullscreen mode Exit fullscreen mode
Output:
NameError: name 'x' is not defined
Enter fullscreen mode Exit fullscreen mode

In this example, we first create a variable x and assign it the value 10. We then use the del keyword to delete the variable. After the variable is deleted, attempting to access it results in a NameError because the variable is no longer defined.

It's important to note that deleting a variable only removes the reference to the value, not the value itself. If other variables reference the same value, the value will still exist in memory. For example, consider the following code:

x = [1, 2, 3]
y = x
del x
print(y)
Enter fullscreen mode Exit fullscreen mode
Output:
[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

In this example, we create a list [1, 2, 3] and assign it to the variable x. We then create another variable y and assign it the value of x, which means that both x and y now reference the same list. When we delete the variable x, the list still exists in memory because it is still being referenced by the variable y. As a result, we can still access the list using the variable y.

Casting

In Python, "casting" refers to the process of converting a value from one data type to another. This can be useful when you need to change the type of a variable to perform a specific operation or to meet the requirements of a function or method.

Here are some examples of casting in Python, using the built-in functions int(), float(), str(), and bool():

# Casting an integer to a float
x = 5
y = float(x)
print(y)
Enter fullscreen mode Exit fullscreen mode
Output:
5.0
Enter fullscreen mode Exit fullscreen mode
# Casting a float to an integer
x = 3.14
y = int(x)
print(y)
Enter fullscreen mode Exit fullscreen mode
Output:
3
Enter fullscreen mode Exit fullscreen mode
# Casting an integer to a string
x = 42
y = str(x)
print(y)
Enter fullscreen mode Exit fullscreen mode
Output:
"42"
Enter fullscreen mode Exit fullscreen mode
# Casting a string to an integer
x = "42"
y = int(x)
print(y)
Enter fullscreen mode Exit fullscreen mode
Output:
42
Enter fullscreen mode Exit fullscreen mode
# Casting a string to a boolean
x = "True"
y = bool(x)
print(y)
Enter fullscreen mode Exit fullscreen mode
Output:
True
Enter fullscreen mode Exit fullscreen mode

In these examples, we use the built-in functions int(), float(), str(), and bool() to cast values from one data type to another. For example, we can cast an integer to a float using the float() function or cast a string to a boolean using the bool() function.

It's important to note that not all values can be cast to all data types. For example, you can't cast a string that contains non-numeric characters to an integer or a float. If you try to do so, you'll get a ValueError.

Conclusion

Variables are an essential part of programming in Python. By understanding the different types of variables and how to use them, you can write more powerful and flexible programs. With the ability to store and manipulate data, you can explore the fascinating world of computation, unlocking new insights and discoveries. By incorporating variables into your code, you can improve its readability and maintainability, making it easier to work with and share with others.

💖 💪 🙅 🚩
enghaon
≀Paulo Portela

Posted on February 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related