Learn all about variables in Python. Learn how to declare, initialize, and use variables effectively. Get tips for naming conventions, data types with hands – on practices in python.
Topics Covered:
- INTRODUCTION
- What Are Variable in Python?
- Key Features of Python Variables
- How to Name Variables
- Types of Variables in Python
- Assigning Values to Variables
- Global and Local Variables
- Python Constants
- Common Mistakes to Avoid
- Conclusion
Python is one of the most popular programming languages today. Its simplicity, versatility, and readability make it an excellent choice for beginners and professionals. One of the foundational concepts in Python is the use of variables. In this article, we will explore what Python variables are, how they work, and how to use them effectively, with simple coding examples.
What Are Variables in Python?
In Python, a variable is like a container for storing data/values. Variables allow you to assign meaningful names to values, making your code easier to read and maintain.
For example:
name = "Ram"
age = 20
is_student = True
Code Explanation:
- name stores the string “Ram”
- age stores the integer 20
- is_student stores the Boolean value True
Key Features of Python Variables
1. Dynamic Typing
Python is a dynamically typed language, which means you do not need to explicitly declare the data type of a variable. Python automatically detects the type based on the value assigned.
x = 100 # x is an integer
x = "hello world!" # Now, x is a string
x = 100.00 # Now x is float
2. Case Sensitivity
Variable names in Python are case-sensitive. For example, Name, name, and NAME are three distinct variables.
3. No Declaration Required
Unlike some programming languages, you do not need to declare a variable before using it. Simply assign a value, and Python will handle the rest.
How to Name Variables
A Good variable name makes your code more readable and maintainable. Here are some common rules and best practices for declaring a variable name:
Rules for Declaring Variable Names
- Variable names must start with a letter (a-z, A-Z) or an underscore (_).
- They cannot start with a number.
- They can only contain letters, numbers, and underscores.
- Keywords like if, else, while and for cannot be used as variable names.
Best Practices
- Use descriptive names: Instead of x, y, or z, use age or weight or total_price.
- Use snake_case or camel case for multi-word names: total_price, user_Name.
- Avoid long names but ensure clarity.
# Good Practice
user_age = 30
total_price = 199.99
# Bad Practice
x = 30
tp = 199.99
Types of Variables in Python
Variables in Python can hold different types of data. Some common types include:
1. Numeric Types
- int: Integer values, ex: 10, 20, -10, -20
- float: Decimal values, e.g:
3.14
,-0.99
a = 10 # int
b = 3.14 # float
2. String
Strings are sequences of characters enclosed in quotes (single, double, or triple).
greeting = "Hello World!" # single line double quote
greeting2 = 'Good Morning!' #single line single quote
multiline = """India is
a great
country.""" #inside triple quote
3. Boolean
Booleans represent True or False.
is_student = True
is_monitor = False
4. Collections
- list: Ordered and mutable collection, e.g: [1, 2, 3]
- tuple: Ordered but immutable collection, e.g: (1, 2, 3)
- dict: Key-value pairs, e.g: {‘name’: ‘Ram’. ‘age’: 12}
numbers = [1, 2, 3]
coordinates = (1, 2, 3)
user = {"name": "Ram", "age": 12}
Assigning Values to Variables
You can assign values to variables using the = operator. Python also supports multiple assignments and swapping of values.
Single Assignment
name = "ram"
age = 20
Multiple Assignment
x, y, z = 10, 20, 30
Swapping Values
a, b = 5, 10
a, b = b, a
Global and Local Variables
Local Variables
Defined inside a function and accessible only within that function.
def greet():
message = "Hello" # Local variable
print(message)
greet()
# print(message) # Error: message is not defined
Global Variables
Defined outside any function and accessible throughout the program.
message = "Hello" # Global variable
def greet():
print(message)
greet()
#output : 'Hello'
counter = 0 # Global variable
def increment():
global counter
counter += 1
increment()
print(counter) # Output: 1
Python Constants
Although Python doesn’t have built-in support for constants, you can use naming conventions to indicate a variable should be treated as constant.
By convention, constants are written in uppercase.
PI = 3.14159
MAX_USERS = 100
Common Mistakes to Avoid
Using Uninitialized Variables
print(x) # Error: x is not defined
2 . Using Keywords
list = [1, 2, 3] # Avoid this
del list # Restore the original list function
Poor Naming Practices
a = 10 #instead give adescriptive variable name
Example: Simple Python Program
Here’s a simple program that demonstrates variable usage:
# Program to calculate the area of a circle
PI = 3.14
radius = float(input("Enter the radius of the circle: "))
area = PI * (radius ** 2)
print(f"The area of the circle with radius {radius} is {area:.2f}")
Conclusion
Variables are a cornerstone of Python programming. Understanding how to use them effectively lays the foundation for building more complex programs. By adhering to best practices, choosing descriptive names, and grasping the nuances of variable types and scopes, we can write cleaner, more maintainable python codes.
You could definitely see your expertise within the paintings you write. The world hopes for even more passionate writers such as you who are not afraid to say how they believe. At all times follow your heart.