How to use Variables in Python
A comprehensive guide

Overview:
Python is a high-level, interpreted programming language that is widely used for a variety of tasks, including web development, data analysis, machine learning, and more. It is known for its simplicity and readability, making it a popular choice for beginners and experienced developers.
One of Python’s key features is its large and supportive community, which has created a vast ecosystem of libraries and frameworks for various tasks. This makes it easy to perform complex tasks with minimal code and also allows for easy integration with other languages and technologies.
Python also has several built-in data types, including integers, floating-point numbers, strings, lists, and dictionaries. It also supports object-oriented, functional, and procedural programming paradigms.
Additionally, Python has a feature called “Pythonic” which is a set of coding conventions and idioms that are considered the most “Pythonic” way of writing code. This makes it easy for developers to read and understand code written by others, regardless of their experience level.
Overall, Python’s flexibility, readability, and large community make it a popular choice for a wide range of tasks, and it is used by many companies and organizations around the world, including Google, NASA, and Spotify.
In Python, indentation is used to indicate the structure of the code and to define blocks of code, such as function and loop bodies. Unlike other programming languages that use curly braces or keywords like “begin” and “end” to indicate the beginning and end of a block, Python relies on indentation.
This means that all statements in a block of code must be indented at the same level and that the level of indentation indicates the level of nesting. For example, in a for loop, the code executed for each iteration of the loop must be indented one level from the for statement. Similarly, in a function definition, the code that makes up the function body must be indented one level from the def statement.
The recommended indentation level is 4 spaces, but it can also be a tab. However, it’s important to be consistent with the indentation level you choose and uses it throughout the codebase.
Here’s an example of a for loop and a function definition to illustrate Python’s indentation scheme:

In this example, the print statement is indented one level from the for statement, indicating that it is part of the loop body. Similarly, the y = x + 1 and return y statements are indented one level from the def statement, indicating that they are part of the function body.
Python’s indentation scheme makes it easy to parse the structure of the code visually and to quickly identify potential errors, such as unindented statements or mismatched indentation levels.
Variable Types:
There are several variables in Python, each with its properties and uses.
· int (integer) — a whole number, positive or negative. Example: x = 5
· float (floating point number) — a decimal number, positive or negative.
Example: y = 0.5
· str (string) — a sequence of characters enclosed in quotation marks.
Example: name = “John Doe”
· bool (boolean) — a true or false value.
Example: is_student = True
· list — an ordered collection of items enclosed in square brackets.
Example: fruits = [“apple”, “banana”, “orange”]
· tuple — an ordered collection of items, enclosed in parentheses.
Example: coordinates = (3, 4)
· dict (dictionary) — an unordered collection of key-value pairs, enclosed in curly braces.
Example: person = {“name”: “John Doe”, “age”: 30}
· set — an unordered collection of unique items enclosed in curly braces.
Example: unique_numbers = {1, 2, 3}
It’s important to note that Python is a dynamically typed language, which means that the type of a variable can change during the program’s execution.
Also, variable names must start with a letter or an underscore and can contain letters, numbers, and underscores. They cannot start with a number and are case-sensitive.
Integers:
In Python, an integer (often shortened to “int”) is a data type that represents a whole number, positive or negative, without a decimal point. Integers are used to perform mathematical operations and to store numerical values.
Here are some examples of how integers are used in Python:
- Mathematical operations: Integers can perform basic operations such as addition, subtraction, multiplication, and division. For example:

2. Comparison: Integers can be used to compare values to check if they are equal, greater than, or less than each other. For example:

3. Indexing: Integers can access elements in a list or string by their index. For example:

4. Control Flow: Integers can be used to control the flow of a program by controlling the number of iterations in loops or the number of conditions in if-else statements. For example:

5. Storage: Integers can be used to store numerical values used in a program, such as the age of a person, the quantity of an item, or the number of points in a game. For example:

Integers are a basic and versatile data type commonly used in Python programs, as they are a fundamental building block for many operations.
Floating point numbers:
In Python, a floating-point number (often shortened to “float”) is a data type that represents a decimal number, positive or negative. Floats are used to perform mathematical operations and to store numerical values that require decimal precision.
Here are some examples of how floats are used in Python:
- Mathematical operations: Floats can perform operations such as addition, subtraction, multiplication, and division. For example:

2. Comparison: Floats can be used to compare values to check if they are equal, greater than, or less than each other. For example:

3. Calculation: Floats can be used to perform more complex mathematical calculations, such as trigonometry, logarithms, and exponents. For example:

4. Storage: Floats can be used to store numerical values that require decimal precision, such as the price of a stock, the temperature of an object, or the weight of an item. For example:

5. Precision: Floats can handle decimal numbers in scientific calculations, financial calculations, physics, etc. where precision is essential.
Floats are a fundamental data type commonly used in Python programs, especially when precision is required. However, it’s important to remember that floating-point arithmetic is not always exact, and it can lead to round-off errors.
Strings:
In Python, a string (often shortened to “str”) is a data type that represents a sequence of characters enclosed in quotation marks. Strings are used to store and manipulate text in a program.
Here are some examples of how strings are used in Python:
- Output: Strings can output messages to the user or display information on the screen. For example:

2. Input: Strings can be used to accept input from the user. For example:

3. Concatenation: Strings can be concatenated (joined) together to create a new string. For example:

4. Formatting: Strings can be formatted to include placeholders for values that will be inserted later. For example:

5. Slicing: Strings can be sliced to extract substrings. For example:

6. Manipulation: Strings can be manipulated using built-in methods such as upper(), lower(), replace(), and many more. For example:

Strings are a fundamental data type commonly used in Python programs to handle and manipulate text. They are versatile, easy to use, and support many operations that make it easy to manipulate and extract information.
In Python, string casing refers to capitalizing letters in a string. Python provides several built-in methods for changing the case of a string.
Here are a few examples:
- The upper() method returns a new string with all characters in uppercase:

2. The lower() method returns a new string with all characters in lowercase:

3. The title() method returns a new string with the first letter of each word in uppercase and the rest of the letters in lowercase:

4. The capitalize() method returns a new string with the first letter of the first word in uppercase and the rest of the letters in lowercase:

5. You can also use the str.swapcase() method that returns a copy of the string with all uppercase characters converted to lowercase and vice versa.

It’s worth noting that all of these methods return a new string; the original string will not be modified.
6. You can also use slicing and concatenation to change the case of a specific part of the string.

These are just a few examples of how you can work with string casing in Python. Understanding how to manipulate strings is an important aspect of programming, and the ability to change the case of a string can be useful in many different situations.
In Python, you can use built-in functions such as int(), float(), and str() to convert a string to an integer, float, or another data type. For example:

- You can also use the eval() function to evaluate a string as a Python expression and return the result. However, the eval() function can be dangerous as it can execute any code passed to it, so it’s recommended to be careful when using it.

2. You can also use the format() method to insert values into a string, commonly used to create formatted strings.

It’s worth noting that when converting a string to a numeric type, it is important to ensure that the string contains a valid number before trying to convert it. Otherwise, a ValueError will be raised.
In summary, string conversion in python is the process of converting a string to a different data type or representation using built-in functions or methods. It allows you to manipulate strings and work with them in different ways, depending on the context of your program.
Boolean:
In Python, a Boolean is a data type with only two possible values: ‘True’ and ‘False’. Boolean values are often used to represent the truth or falsehood of a statement or condition. They are typically used in control flow statements, such as ‘if’ and ‘while’ statements, to determine whether a certain block of code should be executed or not.
Here are some examples of how Booleans are used in Python:
- Comparison: Booleans can be used to compare values to check if they are equal, greater than, or less than each other. For example:

2. Logical Operations: Booleans can be used to perform logical operations such as and, or, not. For example:

3. Control Flow: Booleans can be used to control the flow of a program by controlling the conditions in if-else statements. For example:

4. Loop Control: Booleans can control the loop by controlling the conditions to exit the loop. For example:

5. Boolean Expressions: Booleans can be used to create Boolean expressions that evaluate either True or False. For example:

6. Several operations can be performed on Booleans in Python, such as ‘and’, ‘or’, and ‘not’. Here are some examples:

7. Additionally, you can use comparison operators such as ‘==’, ‘!=’, ‘>’, ‘<’, ‘>=’, and ’<=’ to compare values and return a Boolean. For example:

Boolean values are essential in programming, as they are used to make decisions and control the flow of a program. They are simple to use but powerful, allowing you to make complex decisions with a single line of code.
Lists:
In Python, a list is a collection of items that are ordered and changeable. Lists are written with square brackets [] and items are separated by commas. Lists can contain items of different data types, including numbers, strings, and other lists. Lists are a very powerful tool in Python and are used in many situations, such as storing and manipulating data, looping through elements, and more.
One of the main characteristics of lists is that they are ordered, which means that the items in a list have a specific position or index. The index of the first item in a list is 0, the second item is 1, and so on. You can access items in a list by referring to their index number. Negative indexing is also possible, which allows you to access items from the end of the list.
Lists are also changeable, meaning you can add, remove, or change items in a list after it has been created. You can use methods such as append(), insert(), remove(), and pop() to add or remove items from a list. You can also use the sort() method to sort the items in a list in ascending or descending order.
Lists are also very versatile and can be used in many ways. For example, you can use loops to iterate through the items in a list, use list comprehension to create new lists, use the len() function to find the length of a list, and so on.
Lists are a fundamental and powerful data structure in Python and are used in many different situations. Understanding how to work with lists is essential for any Python developer.
In Python, a list is a collection of items that are ordered and changeable. Lists are written with square brackets [], and commas separate items. Here is an example of a list of integers:

You can access items in a list by referring to the index number:

You can also use negative indexing to access items from the end of the list:

You can change an item in a list by referring to its index:

You can use the len() function to find the length of a list:

You can use the append() method to add an item to the end of a list:

You can use the insert() method to add an item at a specific position in a list:

You can use the remove() method to remove an item from a list:

You can use the pop() method to remove an item at a specific position in a list:

You can use the sort() method to sort a list in ascending order:

You can also use the sort(reverse=True) method to sort the list in descending order.

These are just a few examples of the many things you can do with lists in Python.
Tuples:
A tuple in Python is an ordered, immutable, and heterogeneous collection of elements written as comma-separated values inside parentheses. Tuples can contain elements of different data types, including other tuples, and are used to store multiple related values in a single entity. They can be accessed via indexing and slicing and are commonly used for returning multiple values from a function or grouping data into a single structure.
Here are some code examples for using tuples in Python:
Creating a tuple:

Accessing elements in a tuple:

Modifying a tuple:

Iterating over a tuple:

Dictionaries:
A dictionary in Python is an unordered collection of key-value pairs, where each key is unique and used to retrieve its associated value. Dictionaries are written as key-value pairs within curly braces {} and are separated by colons. They are also mutable, meaning you can add, delete, or modify elements in a dictionary. Dictionaries are commonly used to store and retrieve values by a unique key, similar to a real-world dictionary where words are used to retrieve their meanings.
Here’s an example of creating a dictionary:

Here’s an example of accessing values in a dictionary:

Here’s an example of modifying a dictionary:

Sets:
A set in Python is an unordered collection of unique elements. It is defined using curly braces {} with elements separated by commas or using the built-in set() function. Sets are helpful for removing duplicates from a list or for performing mathematical set operations, such as union and intersection. Sets are mutable and do not allow duplicates, so each element can only appear once in a set.
Here’s an example of creating a set:

Here’s an example of adding elements to a set:

Here’s an example of removing elements from a set:


TL;DR
In Python, there are several types of variables, including:
· int (integer)
· float (floating point number)
· str (string), bool (boolean)
· list
· tuple
· dict (dictionary)
· set
These variables have their properties and use like:
· whole numbers for int
· decimal numbers for float
· sequence of characters for str
· true or false value for bool
· ordered collection for list and tuple
· key-value pairs for dict
· unique items for set
Python is a dynamically typed language, meaning the variable type can change during the program’s execution.
To name a variable, it must start with a letter or underscore, can contain letters, numbers, and underscores, but cannot start with a number, and is case-sensitive.
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
Learn how to create better content for developers with Circuit.