02
MayWhat are Python Variables - Types of Variables in Python Language
Want to know how to save and use values in your Python program? Learn how variables in Python help you store numbers, text, and more in a simple way!
Variables in Python are a core concept in Python programming. They allow you to save data that may be accessed and modified throughout your code. Imagine you have a box where you keep your favorite items, like a book or a toy. In Python, variables work just like that box, but instead of toys, you store data like numbers and text. Learn how variables in Python make your code easier and more organized!
In this Python Tutorial, let's break down the variables in Python in a simple approach.
What are Variables in Python
Variables in Python are used to store and manage data values in your program. A variable in Python is created by assigning a value to a name, and this value can be changed or used later in the code. With variables in Python, you can work with different data types in Python, such as numbers, strings, or lists, making your code more flexible and efficient.
- A variable is a named memory location in which a value is stored.
- Variables are used to store information that will be needed during the program.
- In Python, you do not need to define a variable before using it.
- When you assign a value to a variable, it is created.
- You can change a variable's value at any moment. This will override its previous value.
If you still have the confusion related to datatype in Python, as we have discussed earlier, you can check it once again: Data Types in Python
Python Variable Naming Conventions
When working with variables in Python, it’s essential to follow proper naming conventions to make your code readable and maintainable. Here are some key rules for naming variables in Python
- Variable names should start with a letter (a-z, A-Z) or an underscore (_), followed by letters, numbers, or underscores.
- Variables in Python are case-sensitive, meaning myVariable and myvariable are considered different.
- Avoid using Python keywords or built-in function names (like print, input, etc.) as variable names in Python.
- Use descriptive names for variables in Python to make your code easier to understand. For example, use age instead of x.
- If a variable in Python consists of multiple words, separate them with underscores (snake_case), such as student_score.
- Try to keep variable names in Python short but meaningful, balancing clarity and brevity. For example, count instead of number_of_items.
Declaration and Initialization of Variables in Python
Let's break down the declaration and initialization of variables in Python step by step:
1. Declaration of Variables in Python
In Python, you don’t need to explicitly declare a variable in Python before using it. You simply create a variable in Python by assigning a value to it. This is different from other programming languages, where you usually declare a variable before using it.
Example
age = 25
name = "John"
In the example above, age and name are the variables in Python, and they are automatically declared when assigned the values 25 and "John", respectively.
2. Initialization of Variables in Python
Initialization means giving a value to a variable in Python at the time of its creation. When you assign a value to a variable in Python, you are initializing it.
Example
height = 5.9
is_student = True
Here, height is initialized with the value 5.9, and is_student is initialized with the boolean value True.
3. Assigning Values to Variables in Python
You assign values to variables in Python using the assignment operator =. The value can be of any data type, such as integers, strings, floats, or booleans.
Example
score = 90 # Integer value
greeting = "Hello, World!" # String value
temperature = 98.6 # Float value
is_active = False # Boolean value
The variable score is assigned an integer value of 90, the greeting gets a string"Hello, World!" the temperature gets a float value of 98.6, and is_active is set to False.
4. No Explicit Declaration in Python
Unlike some other languages, you don't have to specify the data type of a variable in Python explicitly. Python automatically understands the type based on the value assigned to the variables in Python.
Example
number = 10 # Python understands this as an integer
name = "Aman" # Python understands this as a string
Here, Python automatically detects that number is an integer and name is a string based on the assigned values.
Example of Declaration and Initialization of Variables in Python Compiler
Let's run this code in the Python Compiler:
# Declare a variable named 'age'
age = 25
# Declare a variable named 'name'
name = "Ram"
# Print the values of the variables 'age' and 'name'
print("My name is", name, "and I am", age, "years old.")
Output
My name is Ram and I am 25 years old.
Explanation
- In the above example, The code declares two variables in Python: age is assigned the value 25 and name is assigned the string "Ram".
- The print() function is used to display the values of these variables in Python, printing the sentence: "My name is Ram and I am 25 years old."
How do you work with Variables in Python?
When you're building a program, variables in Python are used in many smart ways to store, update, and check values. Let’s go through the most common types of variable use in real programs:
1. Expressions with Variables in Python
Expressions are small formulas in coding that are used to perform calculations. These calculations are done using numbers, operators, and variables in Python.
a = 10
b = 20
result = a + b
print(result)
Explanation
- Here, we declare two variables in Python, a and b, and assign them values.
- We create a new variable in Python called result to store the sum of a and b.
Output:
30
2. Counting Things (Counters)
A counter is a variable in Python that increases step by step. It is commonly used inside loops.
count = 0
for i in range(5):
count += 1
print("Count is:", count)
Explanation
- We use a variable in Python called count and set it to 0 before the loop starts.
- Each time the loop runs, the count variable in Python increases by 1.
Output:
Count is: 5
3. Adding Repeated Values (Accumulators)
Accumulators are variables in Python used to collect a running total of values inside loops.
total = 0
for num in [5, 10, 15]:
total += num
print("Total sum is:", total)
Explanation
- We declare a variable in Python named total to store the sum of numbers.
- Inside the loop, we use the total variable in Python to keep adding each number from the list.
Output:
Total sum is: 30
4. Using Temporary Variables
A temporary variable in Python holds data temporarily while values are being swapped or changed.
x = 5
y = 10
temp = x
x = y
y = temp
print("x =", x)
print("y =", y)
Explanation
- The temp variable in Python holds the value of x temporarily.
- We then safely assign new values to x and y using temp.
Output:
x = 10
y = 5
5. True/False Checking (Boolean Flags)
A boolean flag is a variable in Python that tells us if something is true or false.
found = False
for item in [1, 2, 3]:
if item == 2:
found = True
print("Found 2?", found)
Explanation
- We use a found variable in Python to check if number 2 is in the list.
- If the item is found, we set the found variable in Python to True.
Output:
Found 2? True
6. Loop Helper Variables
Loop helper variables in Python help you repeat actions for multiple items in a list.
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
Explanation
- The variable in Python fruit changes on every loop to show each item in the list.
- This variable helps you work with each value one at a time using simple code.
Output:
apple
banana
cherry
7. Data Storage Using Variables in Python
You can use variables in Python to store and manage big data using lists and dictionaries.
students = ["Aman", "Riya"]
marks = {"Aman": 90, "Riya": 85}
print("Students:", students)
print("Marks:", marks)
Explanation
- We use two variables in Python to store student names and their marks.
- Lists and dictionaries are useful variables in Python for storing related data.
Output:
Students: ['Aman', 'Riya']
Marks: {'Aman': 90, 'Riya': 85}
Understanding the Main Features of Variables in Python
When we talk about variables in Python, we are discussing the basic building blocks of any Python program. These variables in Python help us store data, reuse it, and work with it in smart ways. Unlike other languages, variables in Python are flexible, easy to use, and don't need a fixed data type. Understanding how variables in Python work will help you write better, cleaner, and more readable code.
1. How Variables in Python Point to Data Objects
One of the special things about variables in Python is that they store references to data objects rather than the actual data itself. When you assign a value to a variable in Python, you're not copying the data; you're pointing to it.
Example
x = [1, 2, 3]
y = x
y.append(4)
print(x)
Output:
[1, 2, 3, 4]
Explanation
- Variables in Python such as x and y both point to the same list object in memory.
- This shows that variables in Python work as references to data, not as separate containers.
2. Why Variables in Python Can Change Their Data Type
Another great feature of variables in Python is that they are dynamically typed. This means you don't need to declare a data type before using a variable. A variable in Python can first store an integer and then store a string, all without any errors. This makes variables in Python very flexible for both beginners and advanced programmers.
Example
data = 100 # data is an integer
data = "hello" # now data is a string
print(data)
Output:
hello
Explanation:
- Variables in Python do not need a fixed type, which makes them very versatile.
- You can easily reuse the same variable in Python for different types of data as your logic changes.
3. Using Type Hints to Describe Variables in Python
While variables in Python don’t require a declared type, you can still use type hints to make your code easier to read. Type hints show what kind of data each variable in Python is expected to store.
Example
name: str = "Aman"
age: int = 22
print("My name is", name)
print("I am", age, "years old.")
Output:
My name is Aman
I am 22 years old.
Explanation
- Using type hints with variables in Python makes it easier for others to read your code.
- Although not required, type hints improve clarity when you use multiple variables in Python.
Understanding Variable Scopes in Python
Understanding how variables in Python work across different scopes is crucial for writing effective code. Scope determines where a variable in Python can be accessed and modified. Whether you are dealing with global, local, or non-local variables in Python, knowing how the scope works helps avoid errors and unexpected behavior.
1. Global, Local, and Non-Local Variables
In Python, the scope of variables in Python determines where they are accessible. A global variable in Python can be used anywhere in the code, while a local variable in Python is confined to the function or block where it’s defined. Non-local variables in Python are used within nested functions to refer to a variable in the enclosing (but non-global) scope.
Example
x = "global"
def outer():
x = "non-local"
def inner():
nonlocal x
x = "local to outer"
inner()
print("Outer x:", x)
outer()
print("Global x:", x)
Output:
Outer x: local to outer
Global x: global
Explanation:
- This example demonstrates the difference between global, local, and non-local variables in Python.
- By using the nonlocal keyword, we can modify the variable in Python in the outer function scope.
2. Class and Instance Variables (Attributes)
In object-oriented programming with Python, variables in Python can be either class variables or instance variables. Class variables are shared by all instances of a class, while instance variables are specific to each instance of the class. This distinction helps you manage how data is stored and accessed in an object-oriented design.
Example
class Student:
school = "ABC School" # class variable
def __init__(self, name):
self.name = name # instance variable
s1 = Student("Ram")
s2 = Student("Shyam")
print(s1.name, "-", s1.school)
print(s2.name, "-", s2.school)
Output:
Ram - ABC School
Shyam - ABC School
Explanation:
- Variables in Python, like school, are class variables, meaning all instances of the class share them.
- Variables in Python, such as name, are instance variables, and each instance of the class will have its own copy.
3. Deleting Variables From Their Scope
In Python, you can use the del keyword to remove variables in Python from their scope. This is particularly useful when you want to free up memory or ensure that a variable in Python is no longer accessible. Once a variable in Python is deleted, trying to access it will raise an error.
Example
x = 10
print("Before deleting:", x)
del x
# print(x) # This will give an error if uncommented
Output:
Before deleting: 10
Explanation:
- The del keyword removes a variable in Python from the scope where it is defined.
- After deleting a variable in Python, attempting to use it will result in an error.
Different Easy Ways to Create Variables in Python
There are many helpful ways to create and work with variables in Python. These different styles make writing code faster, shorter, and easier to understand.
1. Assigning Many Variables at Once
In this method, you can assign values to multiple variables in Python in a single line. It helps when you need to create many variables in Python quickly and cleanly. This is called parallel assignment and is one of the simplest ways to use variables in Python in a neat format.
a, b, c = 10, 20, 30
print("a =", a)
print("b =", b)
print("c =", c)
Output:
a = 10
b = 20
c = 30
Explanation:
- This code assigns values to three variables in Python at the same time using a single line.
- This method saves space and makes it easy to handle multiple variables in Python together.
2. Unpacking Values from Lists or Tuples
Another cool way to use variables in Python is to unpack them from a list or tuple. When you have a group of values, you can assign them to different variables in Python in one go. This keeps your code short and easy to read, and it's very common in real Python projects that use variables in Python a lot.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output:
apple
banana
cherry
Explanation:
- The list values are unpacked into three variables in Python named x, y, and z.
- This is useful when the number of items matches the number of variables in Python.
3. Creating and Using Variables in One Step
You can also create variables in Python while using them inside an expression. This is called an assignment expression or "walrus operator". It helps when you want to use the value of variables in Python as soon as they are created, especially inside loops or conditions. This method saves time and space while handling variables in Python.
if (n := 5) > 3:
print("n is greater than 3:", n)
Output:
n is greater than 3: 5
Explanation:
- This method creates variables in Python while checking their values in a condition.
- Assignment expressions allow you to save values and use variables in Python right away without repeating code.
Conclusion
In conclusion, variables in Python help us store and work with data easily. We explored simple ways to create variables in Python. Keep practicing and enjoy using variables in Python in your code!
Further Reading Articles |
How Many Keywords in Python (With Examples) |
Understanding Python While Loop with Examples |
Bitwise Operators in Python: Types and Examples |
Test your skills with the following MCQs 🎯
Test your knowledge of Python variables and solidify your understanding of how they work!