Variables in Python
Variables in Python are fundamental building blocks, serving as containers for storing data values. In Python, memory space is allocated automatically without the need for explicit declaration when a value is assigned to a variable. The assignment of values to variables is done using the equal sign (=).
Example of Variable in Python
Python is dynamically-typed, which means you don't need to declare the type of a variable explicitly. Here's an example to illustrate how variables work in Python:
Output:
Variables Assignment
Python simplifies variable assignment, making it easy and intuitive for developers.
Creating Variables
In Python, creating a variable is as simple as assigning it a value. Python is dynamically typed, so you don't need to declare the type. The variable is created the moment you first assign a value to it.
Output:
Python Redeclaring Variables
You can redeclare a variable in Python by assigning a new value to it. This can even change the variable's type, due to Python's dynamic typing.
Output:
Initially, x is an integer. After redeclaration, x becomes a string.
Python Assign Values to Multiple Variables
Python allows assigning values to multiple variables in one line, making your code concise and readable.
Output:
Assigning Different Values to Multiple Variables
You can assign different types of values to multiple variables in a single statement in Python.
Output:
Here, a becomes an integer (5), b a float (3.2), and c a string ("Hello").
Can We Use the Same Name for Different Types?
Yes, in Python, we can use the same variable name for different types. Due to Python's dynamic typing, the type of a variable is inferred from the value assigned, and the type can change as you reassign different values.
output:
+ Operator with Variables
The + operator in Python can be used with variables for addition or concatenation, depending on the data type.
- For numbers, it performs addition:
Output:
- For strings, it performs concatenation:
Output:
Using the + operator between different types (e.g., a string and an integer) without explicit conversion will result in a TypeError.
Global and Local Python Variables
In Python, variables' scope—where they can be accessed—is determined by where they are defined. The two main types of variable scope are global and local.
Global Variables
Global variables are declared outside of functions or in the global scope, meaning they can be accessed throughout your code, including inside functions. They are useful when multiple functions need to access the same data.
Output:
In this example, x is a global variable accessible both inside and outside of the function().
Local Variables
Local variables are declared inside a function and can only be used within that function's scope of variables in python. They are created when the function starts and destroyed when the function ends.
Output:
Here, y is a local variable, only accessible inside function().
Global keyword in Python
The global keyword in Python plays a pivotal role in modifying global variables from within a function's scope. It's used to declare that a variable inside a function is global, not local, allowing you to update the global variable's value from within the function.
Example
Without the global keyword, any variable assigned a value within a function is assumed to be local unless explicitly declared as global.
Output:
In this example, the global keyword allows the change_global_x function to modify the global variable x.
Types of variables in python
Python variables can also hold different types of data. Here are some common types along with a single example for each, showcasing how they are used and their typical output:
Integers (int)
Integers are whole numbers without a fractional component.
Floating Point Numbers (float)
Floats are real numbers; they include a decimal point to represent fractions.
Strings (str)
Strings consist of character sequences, utilized for depicting text.
Booleans (bool)
Booleans represent one of two values: True or False.
Lists
Lists are sequences of elements that maintain an order and can contain items of various types.
Tuples
Tuples resemble lists in many aspects, yet they are immutable, signifying that once created, they cannot be altered.
Dictionaries (dict)
Dictionaries hold key-value pairs. Keys must be unique and immutable.
Sets
Sets are unordered collections of unique elements.
Each of these variable types serves different purposes in Python programming, allowing for a flexible approach to solving a wide array of problems.
Delete a variable
Just like declaring and using variables in Python is so easy, even deleting a Python variable is not a difficult task either.
Python automatically removes variables and functions from memory when they are no longer in use, thereby liberating space. Users have the option to manually eliminate variables and functions as well. This feature is particularly beneficial when substantial data structures become redundant, as their deletion liberates memory for alternative applications. This is the rationale behind Python providing the delete feature to its users.
You can delete a variable using the del command in Python.
Let’s take a look at how we do it practically and what is the output that we get –
Here, we have re-used our total number of chocolates example. We declared it initially and now we are deleting it.
Output –
Using the del command, we have successfully deleted the variable no_of_chocolates.
Object References
The topic of variables in Python is incomplete without understanding how the Python interpreter works when we declare a variable. It is slightly different when compared to other programming languages.
We all know that Python is an object-oriented language. Hence, every object belongs to a specific class.
Consider the following example –
We have declared a variable and assigned a string in the above example. Now, we print it to the console first. In the last line of the code, you will notice that we have used the type function.
What is the type function doing? Let’s take a look –
We can see that a string object is created of the class str! Thus, we can say that variables in Python are symbolic names that point to an object, just like the example we looked at.
FAQ
Q. What is a variable in Python?
A. In Python, a variable acts as a storage space in memory designated to hold values. Essentially, it serves as a means for a Python program to present data for the computer to process.
Q. How do you create a variable in Python?
A. Creating a variable in Python is straightforward. You assign a value to a variable name, and Python automatically declares the variable with that value. For example:
Q. Can variable names in Python start with a number?
A. No, variable names cannot start with a number. They must start with a letter or an underscore. For example, _myvar and myvar are valid, but 1myvar is not.
Q. Are Python variable names case-sensitive?
A. Yes, variable names in Python are case-sensitive. For instance, myVar and myvar would be treated as two distinct variables.
Q. What are global and local variables in Python?
A. Global variables are defined outside of functions and can be accessed anywhere in the program. Local variables are defined inside functions and can only be used within that function.
Q. How can you update a global variable from inside a function?
A. You can update a global variable from inside a function using the global keyword before the variable name. For example:
Q. What data types can Python variables store?
A. Python variables can store various data types, including integers, floating-point numbers, strings, booleans, lists, tuples, sets, and dictionaries.
Q. Can a single Python variable store multiple values?
A. Yes, using data types like lists, tuples, sets, and dictionaries, a single Python variable can store multiple values. For example:
Q. How do you delete a variable in Python?
A. You can delete a variable in Python using the del keyword. For example:
Q. Can Python variables change type?
A. Yes, Python variables can change type. Python is dynamically typed, so you can reassign a variable to a value of a different type. For example:
Conclusion
- What are variables in Python?, Variables in Python are named memory locations used to store data.
- A variable is used to retrieve the stored data, and its value may change during the program.
- We use the “=” operator for value assignment.
- Python automatically releases the memory occupied by variables and functions when they are no longer needed, thereby reclaiming the resources.
- You can manually delete a variable using the del command in Python.
That’s all for today, folks! Happy coding!