What are Python Variables?

Python variables are like containers that allow you to store and manipulate data. Just like the name suggests, they can vary, meaning you can assign different values to them throughout your program. Variables give you the power to hold various types of information, such as numbers, text, and even more complex data structures.

In this Python helper tutorial, we’ll explore the ins and outs of variables in Python, why they are essential, and the different types you can use. So, let’s get started and unlock the potential of Python variables together!

How to Declare variable in Python?

To declare a variable in Python, all you need to do is pick a name for your variable and give it a value using the equals sign =. It’s as simple as that!

For example, let’s say you want to declare a variable to store someone’s name. You can do it like this:

name = "Miller"

In this case, we’ve declared a variable called name and assigned it the value Miller. It’s just like saying, “Hey Python, I want to create a variable called name, and I’m giving it the value Miller.”

Now imagine you’re planning a trip to two popular destinations: Paris and New York. You can use variables to store the names of these cities:

destination1 = "Paris" destination2 = "New York"

So feel free to create variables with names that make sense to you and assign them values that match what you’re working with.

Why Does Python Use Variables?

Python utilizes variables to make your code more flexible and dynamic. They provide a way to store data temporarily or permanently, depending on your needs. By using variables, you can manipulate and transform information, perform calculations, and create more complex programs.

Let’s say you want to calculate the average age of two well-known celebrities. You can assign their ages to variables and perform the calculation:

Example Code
age_celebrity1 = 35 age_celebrity2 = 42 average_age = (age_celebrity1 + age_celebrity2) / 2 print("The average age of the celebrities is:", average_age)

Here, we assigned the ages of two celebrities to variables, calculated the average, and displayed the result using the print statement.

Variable Naming in Python

When it comes to naming Python variables, it’s crucial to choose names that are meaningful and descriptive. By using clear and intuitive variable names, you make your code more readable and easier to understand. One of the golden rules of variable naming is to use names that clearly indicate the purpose or content of the variable. For example, if we want to store the name of a celebrity, we can use a variable name like celebrity_name:

Example Code
celebrity_name = "Jennifer Lopez" print("The celebrity's name is", celebrity_name)

In this example, we’ve chosen a descriptive name, celebrity_name, to represent the name of a celebrity. By using clear and meaningful variable names, we can easily understand the purpose of the variable.

Camel Case or Underscores

Python offers different naming conventions, such as camel case and underscores. The choice between these conventions is mainly a matter of personal preference. For instance, if we want to store the age of a celebrity, we can use either celebrityAge (camel case) or celebrity_age (underscores):

Example Code
celebrityAge = 42 print("The celebrity's age is", celebrityAge)

Or:

Example Code
celebrity_age = 42 print("The celebrity's age is", celebrity_age)

Both options are valid, but consistency is key. It’s essential to choose one convention and stick with it throughout your codebase. By choosing descriptive names, following a consistent naming convention, and avoiding reserved words, you can make your code more readable and maintainable.

What Are Python Variable Types?

Python provides various variable types that allow you to store and manipulate different kinds of data. Whether you’re working with numbers, text, or complex data structures, understanding the different variable types will empower you to write more efficient and effective code.

Let’s dive in and discover the world of Python variable types!

Numeric Variables

Numeric variables in Python are used to store numeric values such as integers, floating-point numbers, and complex numbers. Let’s say we have a variable called age to store the age of a celebrity. Here’s an example:

Example Code
age = 42 print("The celebrity's age is", age)

In this example, we assign the value 42 to the variable age. The print() statement will displays below output:

Output
The celebrity’s age is 42

String Variables

String variables are used to store text data. Let’s use a popular place like New York City as an example:

Example Code
city = "New York City" print("I dream of visiting", city)

In this example, the variable city holds the value “New York City” but the print() statement will outputs:

Output
I dream of visiting New York City

Boolean Variables

Boolean variables can hold either True or False values. Let’s consider a scenario where we want to check if a celebrity is famous:

Example Code
is_famous = True if is_famous: print("This celebrity is famous!") else: print("This celebrity is not famous.")

Here, the variable is_famous is set to True, indicating that the celebrity is indeed famous. The if statement checks the value of is_famous and displays the appropriate output.

List Variables

List variables allow us to store multiple values in a single variable. Let’s use a list of celebrities as an example:

Example Code
celebrities = ["Tom Hanks", "Jennifer Lopez", "Brad Pitt"] print("My favorite celebrities are:", celebrities)

In this example, the variable celebrities holds a list of three celebrity names. The print() statement outputs:

Output
My favorite celebrities are: [Tom Hanks, Jennifer Lopez, Brad Pitt]

Dictionary Variables

Dictionaries are used to store key-value pairs. Let’s create a dictionary of famous landmarks:

Example Code
landmarks = {"Eiffel Tower": "Paris", "Statue of Liberty": "New York"} print("Famous landmarks:", landmarks)

Here, the variable landmarks stores the names of famous landmarks as keys and their corresponding locations as values. The print() statement displays the dictionary as:

Output
Famous landmarks: {‘Eiffel Tower’: ‘Paris’, ‘Statue of Liberty’: ‘New York’}

Now that you’ve got the basics of Python variables down, it’s time to take your skills to the next level and dive deeper into advanced learning. We’re thrilled to see you eager to explore more! In this section, we’ll introduce you to some advanced concepts and techniques that will expand your understanding and capabilities in working with variables.

Understanding Global Variables

Global variables are accessible throughout your entire code, regardless of where they are defined. They are like superstars that everyone can see and interact with. Let’s dive into an example:

Imagine we have a global variable called favorite_celebrity that stores the name of your favorite celebrity. We can declare it outside of any functions, making it accessible from anywhere in the code:

Example Code
favorite_celebrity = "Jennifer Lopez" def print_favorite_celebrity(): print("Our favorite celebrity is", favorite_celebrity) print_favorite_celebrity() # Output: Our favorite celebrity is Jennifer Lopez

In this example, we declare the global variable favorite_celebrity and assign it the value Jennifer Lopez. The function print_favorite_celebrity() is then defined to print the value of the global variable. When we call the function, it displays Our favorite celebrity is Jennifer Lopez because the global variable is accessible inside the function.

Exploring Local Variables

Unlike global variables, local variables are confined to a specific scope or context. They are like secret agents that only operate within a restricted area. Let’s continue with our celebrity-themed scenario to understand local variables better.

Suppose we have a function called celebrity_greeting() that prints a personalized greeting to a celebrity. Inside the function, we’ll have a local variable called celebrity_name that stores the name of the celebrity being greeted:

Example Code
def celebrity_greeting(): celebrity_name = "Tom Hanks" print("Hello", celebrity_name, "! You're an amazing actor.") celebrity_greeting() # Output: Hello Tom Hanks! You're an amazing actor.

In this example, the local variable celebrity_name is declared within the function celebrity_greeting(). It holds the value Tom Hanks and is only accessible within the function. When we call the function, it prints the greeting using the value of the local variable.

Understanding the Scope

The scope of a variable refers to the part of the code where the variable is visible and accessible. Global variables have a global scope, meaning they can be accessed from anywhere in the code. On the other hand, local variables have a local scope, limited to the block of code where they are defined, such as within a function.

It’s important to note that local variables take precedence over global variables within the same scope. Let’s see an example to understand this concept:

Example Code
favorite_celebrity = "Jennifer Lopez" def print_favorite_celebrity(): favorite_celebrity = "Brad Pitt" print("Our favorite celebrity is", favorite_celebrity) print_favorite_celebrity() # Output: Our favorite celebrity is Brad Pitt print("But globally, our favorite celebrity is still", favorite_celebrity) # Output: But globally, our favorite celebrity is Jennifer Lopez

In this example, we have a global variable favorite_celebrity set to Jennifer Lopez. Inside the print_favorite_celebrity() function, we define a local variable with the same name, but with the value Brad Pitt. When we call the function, it uses the value of the local variable, giving us the output Our favorite celebrity is Brad Pitt. However, outside the function, when we print the global variable, we still get Jennifer Lopez.

Awesome job! You’ve successfully acquired a strong grasp of global and local variables in Python. With this knowledge, you now have the power to organize your code effectively and ensure that variables are accessible in the right places. But wait, there’s more to discover! Let’s take the next step in our Python variable journey and explore constants and immutable variables.

Constants – Unchanging Values

Constants are special variables that hold values that should remain constant throughout the program. They are like steadfast landmarks that never change in popular places. Let’s dive into an example:

Imagine we want to define a constant called CELEBRITY_OF_THE_DAY that stores the name of a celebrity chosen for the day. We can declare it using uppercase letters to indicate its constant nature:

Example Code
CELEBRITY_OF_THE_DAY = "Jennifer Lopez" print("Today's celebrity is", CELEBRITY_OF_THE_DAY)

In this example, we’ve defined a constant CELEBRITY_OF_THE_DAY and assigned it the value Jennifer Lopez. By convention, constants are written in uppercase letters to distinguish them from regular variables. You can imagine saying, Hey Python, today's celebrity is Jennifer Lopez, and this value will remain constant throughout the program.

To understand constants in python deeply, check our article on python constants.

Exploring Immutable Variables: Unmodifiable Data

Immutable variables, as the name suggests, are variables whose values cannot be modified once assigned. They are like precious artifacts in famous places that cannot be altered. Let’s continue with our celebrity-themed scenario to understand immutable variables better.

Suppose we want to create an immutable variable to represent the age of a celebrity. We can use the tuple data structure, which is immutable, to store the celebrity’s name and age together:

Example Code
celebrity_info = ("Tom Hanks", 65) print("The celebrity is", celebrity_info[0], "and their age is", celebrity_info[1])

In this example, we’ve created a tuple called celebrity_info that contains the name Tom Hanks and the age 65. Tuples are immutable, meaning their values cannot be changed once assigned. You can imagine saying, Hey Python, the celebrity's name is Tom Hanks, and their age is 65. This information is set and cannot be modified.

Benefits of Constants and Immutable Variables

Constants and immutable variables bring several benefits to your Python code. They ensure data integrity by preventing accidental changes to important values. Additionally, they improve performance because Python can optimize immutable objects more efficiently.

By using constants, you can easily manage values that should remain unchanged throughout your program. This promotes clarity and reduces the risk of introducing bugs due to inadvertent modifications.

Similarly, immutable variables provide reassurance that certain data will remain unmodified. This is particularly useful when dealing with shared data or when you want to enforce data integrity.

Congratulations! You’ve now unlocked the secrets of constants and immutable variables in Python. Have you ever wondered how you can modify the value of a variable or assign it a new value? Well, Next we’ll explore these concepts together.

Variable Reassignment: Embracing Change

Python variables are flexible entities that can be reassigned with different values. They are like versatile chameleons that can change their colors. For example:

Imagine we have a variable called favorite_celebrity that initially stores the name of your all-time favorite celebrity, Jennifer Lopez:

Example Code
favorite_celebrity = "Jennifer Lopez" print("My favorite celebrity is", favorite_celebrity)

In this example, we’ve assigned the value Jennifer Lopez to the variable favorite_celebrity. However, if our preferences change and we want to update our favorite celebrity to Tom Hanks, we can simply reassign the variable:

Example Code
favorite_celebrity = "Jennifer Lopez" favorite_celebrity = "Tom Hanks" print("My favorite celebrity is", favorite_celebrity)

By reassigning the variable favorite_celebrity to Tom Hanks, we’ve effectively updated the value. Now, when we print the variable, it will display:

Output
Now my favorite celebrity is Tom Hanks

It’s as simple as that!

Updating Values: Building on Existing Data

Sometimes, instead of completely reassigning a variable, you may want to update its value based on its current value or perform some calculations. Python provides convenient ways to achieve this. Let’s continue with our previous examples scenario to understand updating values better.

Suppose we have a variable called age that stores the current age of a celebrity. We want to increase the age by 5 years. Here’s how we can accomplish this:

Example Code
age = 35 print("The current age is", age) age += 5 print("After 5 years, the age will be", age)

In this example, we start with an initial age of 35. Using the += operator, we update the value of the age variable by adding 5 to its current value. The output will display:

Output
After 5 years, the age will be 40

By updating the value, we can perform calculations or make incremental changes based on existing data.

Deleting Variables in Python

Python variables are like items in your favorite playground. Sometimes, you might want to clean up and remove certain items that are no longer needed. The same goes for variables. Imagine we have a variable called current_celebrity that stores the name of the current trending celebrity:

Example Code
current_celebrity = "Jennifer Lopez" print("The current trending celebrity is", current_celebrity)

In this example, we’ve defined a variable current_celebrity and assigned it the value Jennifer Lopez. However, if the trend changes or we simply want to remove the variable, we can delete it using the del keyword:

Example Code
current_celebrity = "Jennifer Lopez" del current_celebrity print("The current trending celebrity is", current_celebrity)

By using del followed by the variable name, we effectively delete the variable current_celebrity. Now, if we try to print the variable, we’ll encounter an error since it no longer exists. It’s like saying, “Hey Python, we no longer need the variable current_celebrity, so please remove it from our playground.”

Deleting variables not only removes unwanted data but also frees up memory space, allowing your program to run more efficiently. It’s like decluttering your workspace to make room for new ideas.

Suppose we have a large dataset containing information about celebrities. We load this dataset into a variable called celebrity_data to perform some operations:

celebrity_data = load_large_dataset()
# Perform some operations using the celebrity_data

# After we're done, we can delete the variable to free up memory
del celebrity_data

In this example, we load a large dataset into the celebrity_data variable. Once we’re done working with the data, we no longer need it, so we delete the variable using del celebrity_data. By doing so, we free up memory space that was previously occupied by the dataset. This allows other parts of our program to utilize the available memory more efficiently, resulting in better performance.

Congratulations! You’ve gained a solid understanding of Python Variables. From understanding different variable types and their usage to exploring variable reassignment, updating values, and deleting variables, you’ve acquired valuable knowledge to enhance your Python programming skills. So, go ahead and put your newfound knowledge to use. Whether you’re building web applications, analyzing data, or automating tasks, Python offers a wide range of possibilities.

Happy coding, and may your Python journey be filled with exciting discoveries and successful projects!

 
Scroll to Top