Now that we’re familiar with the Jupyter Notebook interface and basic cell inputs, it’s time to dip our feet into Python programming in earnest. To get started with data science’s favorite programming language, it’s essential to develop a working knowledge of variables.
In the realm of programming, variables are one of the most fundamental concepts. They serve as the building blocks for storing and manipulating data within a program. Whether you’re writing a simple script to automate a task or developing a complex software application, understanding how to effectively use variables is crucial. In Python, variables are highly versatile and can hold various types of data, from numbers and text to more complex data structures.
This post aims to provide a comprehensive introduction to variables in Python. I’ll explore what variables are, how they are used, the rules for naming them, and the different types of variables you can work with. By the end of this guide, you’ll have a solid understanding of variables and how to use them effectively in your Python programs.
What is a Variable?
In programming, a variable is a named storage location in memory that holds a value. This value can be anything from a number to a string of text, and it can be changed throughout the execution of a program. Think of a variable as a labeled box that you can store data in, retrieve data from, and modify as needed.
Variables are essential because they allow programmers to write flexible and dynamic code. Instead of hardcoding values directly into your program, you can use variables to store these values and then reference them by name. This makes your code easier to read, maintain, and modify.
For example, consider a simple calculation. If you want to add two numbers, you could directly write 3 + 5 in your code. However, if you store these numbers in variables, you can easily change the numbers later without having to modify the actual calculation:
x = 3 y = 5 result = x + y print(result) # Output will be 8
In this example, x and y are variables that hold the values 3 and 5, respectively. The result of their addition is stored in the variable result, which is then printed to the screen.
How Variables are Used in Python
As you might imagine based on the previous explanation, the use of variables is an indespensible part of data science operations in Python. Here are some ways that you’ll be using them as we go along:
- Storing Data
Variables are primarily used to store data that your program will manipulate. For instance, you might store a user’s input, a calculation result, or data fetched from a database in a variable.
Example:
user_name = "Alice" age = 30
After this input, running a Jupyter Notebook cell that calls out the variable names will output the respective values assigned to them.
- Manipulating Data
Variables allow you to perform operations on the stored data. This includes arithmetic operations, string concatenation, and more complex transformations.
Example:
x = 10 y = 5 z = x * y # z will be 50
- Control Flow
Control flow statements are constructs in programming that enable you to dictate the order in which statements and instructions are executed in your code. They allow your program to make decisions, repeat certain operations, and execute different code paths based on specific conditions. Loops and conditional statements (if, else, elif) are common examples of control flow statements.
Variables can be used in control flow statements to make decisions based on the stored values. This includes using variables in conditions for if, for, and while loops. For example:
threshold = 50 value = 75 if value > threshold: print("Value exceeds threshold")
- Function Parameters and Return Values
Variables are crucial for functions, where they serve as parameters and return values. This allows you to create reusable code blocks that can operate on different data.
def add(a, b): return a + b
result = add(3, 4) # result will be 7
- Data Structures
Variables are also used to store data structures like lists, dictionaries, and tuples, which can hold multiple values and complex data types.
fruits = ["apple", "banana", "cherry"] person = {"name": "Bob", "age": 25}
By understanding these use cases, you can see how variables form the backbone of any Python program, enabling dynamic and flexible code.
Naming Variables
Naming variables is an important aspect of writing clear and maintainable code. Python has specific rules and conventions for naming variables, and adhering to these can help make your code more readable and consistent.
Rules for Naming Variables
- Start with a Letter or Underscore. Variable names must begin with a letter (a-z, A-Z) or an underscore (_). They cannot start with a number.
valid_name = 10 _underscore = 20
- Followed by Letters, Numbers, or Underscores. After the initial letter or underscore, variable names can contain letters, numbers (0-9), or underscores.
name1 = "Alice" age_30 = 30
- Case Sensitivity. Variable names are case-sensitive, meaning age and Age would be considered two different variables.
age = 25 Age = 30
It can be challenging to get used to these rules, especially if Python is your first programming language. However, it gets easier the more that you code and you should get comfortable with Python’s variable naming quirks in a week or so if you practice consistently.
Allowed Character Types
Just like any programming language, Pythom allows the use of most alphanumeric characters on the keyboard, though some symbols here and there are off-limits. Here’s a quick rundown:
- Both uppercase and lowercase letters are allowed.
- Can be used but not as the first character.
- Can be used to separate words for better readability.
Best Practices for Naming Variables
To make sure that your coding gets progressively cleaner, more readable and more efficient, keep the following best practices in mind:
- Use Descriptive Names. Choose variable names that clearly describe the purpose of the variable. This makes your code more understandable.
user_age = 25 total_price = 100.50
- Practice Consistency. Use a consistent naming convention throughout your code. Common conventions include:
- S Words are separated by underscores (e.g., user_age). This is the preferred style for Python variables.
- Each word starts with a capital letter without underscores (e.g., UserAge). This is less common in Python but used in other languages.
- Avoid Reserved Words. Python has a set of reserved keywords that cannot be used as variable names (e.g., class, def, return).
- Make Them Short but Meaningful. While names should be descriptive, they should also be concise to keep the code clean and readable.
sum_total = 100 # Good s = 100 # Too short and unclear
By following these rules and best practices, you can ensure that your variable names are not only valid but also clear and helpful for anyone reading your code.
Types of Variables
In Python, variables can hold data of different types. Understanding these types is crucial for writing effective and efficient code. Here, we will enumerate and define the main types of variables, along with examples for each.
- Integer (int)
Integers are whole numbers, positive or negative, without a fractional part.
Example:
age = 30 year = 2023
- 2. Floating Point (float)
Floating point numbers are numbers that contain a decimal point.
Example:
height = 5.9 weight = 70.5
- 3. String (str)
Strings are sequences of characters enclosed in single, double, or triple quotes.
Example:
name = "Alice" greeting = 'Hello, World!'
- Boolean (bool)
Booleans represent one of two values: True or False.
Example:
is_active = True is_admin = False
- List (list)
Lists are ordered collections of items, which can be of different types. Lists are mutable, meaning they can be changed after creation.
Example:
fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5]
- Tuple (tuple)
Tuples are similar to lists but are immutable, meaning they cannot be changed after creation.
Examples:
coordinates = (10.0, 20.0) colors = ("red", "green", "blue")
- Dictionary (dict)
Dictionaries are collections of key-value pairs. Each key is unique, and they can be of any immutable type.
Example:
person = {"name": "Bob", "age": 25} settings = {"volume": 10, "brightness": 70}
- Set (set)
Sets are unordered collections of unique items.
Example:
unique_numbers = {1, 2, 3, 4, 5} vowels = {"a", "e", "i", "o", "u"}
Code assigning values to various variables can be input in a single code cell. While I personally don’t prefer to do it this way, it’s technically possible and there are scenarios where it’s more practical compared to creating variables on a per code cell basis.
# Integer age = 30
# Float height = 5.9
# String name = "Alice"
# Boolean is_active = True
# List fruits = ["apple", "banana", "cherry"]
# Tuple coordinates = (10.0, 20.0)
# Dictionary person = {"name": "Bob", "age": 25}
# Set unique_numbers = {1, 2, 3, 4, 5}
# Print all variables print(age) print(height) print(name) print(is_active) print(fruits) print(coordinates) print(person) print(unique_numbers)
By understanding and using these different variable types, you can handle a wide range of data in your Python programs.
The Equals Sign as the Assignment Operator
In Python, the equals sign (=) is used as the assignment operator. This operator assigns the value on the right-hand side to the variable on the left-hand side. The process of assignment is straightforward, but it’s crucial to understand as it forms the basis for working with variables.
Example of Assigning a Value to a Variable
Here’s a simple example to illustrate how the assignment operator works:
# Assigning values to variables name = "Alice" age = 30 height = 5.7
# Printing the values print(name) # Output: Alice print(age) # Output: 30 print(height) # Output: 5.7
Explanation
- Assigning a String
name = "Alice"
Here, the string “Alice” is assigned to the variable name. The variable name now holds the value “Alice”.
- Assigning an Integer
age = 30
The integer 30 is assigned to the variable age. The variable age now holds the value 30.
- Assigning a Float
height = 5.7
The float 5.7 is assigned to the variable height. The variable height now holds the value 5.7.
- Printing the Values
print(name) # Output: Alice print(age) # Output: 30 print(height) # Output: 5.7
The print() function is used to display the values stored in the variables. The output shows the values that have been assigned to name, age, and height.
The assignment operator can be used with different data types, and you can reassign new values to existing variables at any time. For example:
age = 30 age = 31 # The variable 'age' now holds the value 31
In this case, the value of age is updated from 30 to 31.
Using a Variable in a Print Statement
One of the common operations in Python is printing the values of variables to the console. This is often done for debugging purposes, to provide user feedback, or simply to display results. The print() function in Python is used to output data to the standard output, usually the console.
Concept
The print() function can take multiple arguments, including strings and variables. When you pass a variable to print(), it displays the value of that variable. You can also combine variables and strings to create informative messages.
Possible Use Case
Consider a scenario where you want to display a user’s name and age. Instead of hardcoding these values into your print statement, you can store them in variables and then print them, which makes your code more flexible and maintainable.
Example
Here’s an example that demonstrates how to use variables in a print() statement:
# Assign values to variables name = "Alice" age = 30
# Print the values of the variables print("Name:", name) print("Age:", age)
# Print a formatted string that includes the variables print(f"{name} is {age} years old.")
Explanation
- Printing Variables Directly
print("Name:", name) print("Age:", age)
Here, print(“Name:”, name) prints the string “Name:” followed by the value of the name variable. Similarly, print(“Age:”, age) prints the string “Age:” followed by the value of the age variable.
- Formatted String
print(f"{name} is {age} years old.")
Using an f-string (formatted string), you can embed expressions inside string literals using curly braces {}. This allows you to construct a string that includes the values of name and age.
Output
When the above code is executed, the output will be:
Name: Alice Age: 30 Alice is 30 years old.
By using variables in print statements, you can create dynamic and informative output that reflects the current state of your program’s data. This practice is especially useful for debugging and for providing users with meaningful information.
Wrapping It Up
Understanding variables is a foundational skill in Python programming and an essential part of any programmer’s toolkit. Variables allow you to store and manipulate data, making your code dynamic and flexible. By following best practices for naming variables, recognizing the different types of variables, and using the assignment operator effectively, you can write clear, maintainable, and efficient Python code.
As you continue your journey in Python programming, remember that mastering variables will significantly enhance your ability to solve problems and develop robust applications. Keep experimenting with different types of variables and use cases, and you’ll soon find yourself writing more complex and powerful programs with ease.