Python: A Guide to Variables
≀Paulo Portela
Posted on February 15, 2024
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)
Output:
Euclid
# Boolean variable
is_prime = True
print(is_prime)
Output:
True
# Integer variable
perfect_number = 6
print(perfect_number)
Output:
6
# Float variable
pi = 3.14159
print(pi)
Output:
3.14159
# Complex variable
c = 3 + 4j
print(c)
Output:
(3+4j)
# Tuple variable
dimensions = (3, 4, 5)
print(dimensions)
Output:
(3, 4, 5)
# Set variable
primes = {2, 3, 5, 7}
print(primes)
Output:
{2, 3, 5, 7}
# List variable
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13]
print(fibonacci)
Output:
[0, 1, 1, 2, 3, 5, 8, 13]
# Dictionary variable
math_constants = {"pi": 3.14159, "e": 2.71828, "phi": 1.61803}
print(math_constants)
Output:
{'pi': 3.14159, 'e': 2.71828, 'phi': 1.61803}
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 variablemathematician
and assign the value "Euclid
" to it.Boolean: A boolean is a data type that can have one of two values:
True
orFalse
. Booleans are often used to represent the truth value of a condition or expression. In the example above, we create a boolean variableis_prime
and assign the valueTrue
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 variableperfect_number
and assign the value6
to it.Float: A
float
is a number with a decimal point, used to represent real numbers. In Python, floats are represented using thefloat
data type. In the example above, we create a float variablepi
and assign the value3.14159
to it.Complex: A complex number is a number that can be expressed in the form
a + bj
, wherea
andb
are real numbers andj
represents the square root of-1
. In Python, complex numbers are represented using thecomplex
data type. In the example above, we create a complex variablec
and assign the value3 + 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 variabledimensions
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 variableprimes
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 variablefibonacci
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 variablemath_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))
Output:
<class 'int'>
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)
Output:
10
del x
print(x)
Output:
NameError: name 'x' is not defined
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)
Output:
[1, 2, 3]
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)
Output:
5.0
# Casting a float to an integer
x = 3.14
y = int(x)
print(y)
Output:
3
# Casting an integer to a string
x = 42
y = str(x)
print(y)
Output:
"42"
# Casting a string to an integer
x = "42"
y = int(x)
print(y)
Output:
42
# Casting a string to a boolean
x = "True"
y = bool(x)
print(y)
Output:
True
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.
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
November 12, 2024