Contents:
- What is a Variable in Python?
- Key Features of Python Variables
- Variable Naming Rules and Conventions
- Assigning Values to Variables
- Multiple Assignments in Python
- Type Casting a Variable in Python
- Constants in Python
- Deleting a Variable in Python
- Scope of a Variable in Python
- FAQs on Python Variables
What is a Variable in Python?
In Python, a variable is a name that refers to a value stored in memory. It acts as a container to store data, which can be changed during program execution.
Example:
sanfoundry_course = "Python Programming" sanfoundry_duration = 30 print("Course:", sanfoundry_course) print("Duration:", sanfoundry_duration, "days")
Output:
Course: Python Programming
Duration: 30 daysKey Features of Python Variables
- No Explicit Declaration – Python automatically determines a variable’s type when you assign a value. No need for manual type declarations.
- Dynamic Typing – A variable can store different types of data and even change its type during execution. For example, a variable can hold a number first and a string later.
- Case-Sensitive – Python treats uppercase and lowercase letters differently. var and Var are two separate variables.
- Assignment Operator (=) – The equal sign assigns values to variables. Example: x = 10 stores 10 in x.
- Automatic Memory Management – Python manages memory by automatically deleting unused variables with a garbage collector, reducing manual cleanup.
- Multiple Assignments – You can assign values to multiple variables in one line. Example: a, b, c = 5, “hello”, 3.14 assigns different values to a, b, and c.
Variable Naming Rules and Conventions
Python has certain rules and best practices for naming variables:
- Variable names must start with a letter (a-z, A-Z) or an underscore (_).
- They can contain letters, numbers (0-9), and underscores (_).
- They are case-sensitive (e.g., myVar and myvar are different).
- Avoid using Python reserved keywords (e.g., if, else, class).
- Use descriptive names (e.g., user_age instead of ua).
- Cannot start with a number.
Assigning Values to Variables
In Python, assigning values to variables is done using the = operator. Python automatically determines the data type.
Example:
sanfoundry_course = "Python" # String sanfoundry_duration = 30 # Integer sanfoundry_rating = 4.9 # Float sanfoundry_active = True # Boolean print(sanfoundry_course) print(sanfoundry_duration) print(sanfoundry_rating) print(sanfoundry_active)
Output:
Python 30 4.9 True
Multiple Assignments in Python
Python allows assigning values to multiple variables in a single line using multiple assignments. This makes code more concise and readable.
1. Assigning Multiple Variables in One Line
course, level, duration = "Python", "Beginner", 30 print(course, level, duration)
Output:
Python Beginner 302. Assigning Same Value to Multiple Variables
The same value can be assigned to multiple variables simultaneously.
x = y = z = "Sanfoundry" print(x, y, z)
Output:
Sanfoundry Sanfoundry Sanfoundry
3. Reassigning Variables
Variables can be reassigned with a different value or data type.
sanfoundry_topic = "Machine Learning" print(sanfoundry_topic) sanfoundry_topic = 2025 # Reassigned with an integer print(sanfoundry_topic)
Output:
Machine Learning
20254. Swapping Variables
Swap values of two variables without a temporary variable:
x, y = 10, 20 x, y = y, x print("After Swap: x =", x, ", y =", y)
Output:
After Swap: x = 20 , y = 10
Type Casting a Variable in Python
Type casting (also known as type conversion) in Python is used to convert one data type into another. Python provides built-in functions for this purpose.
Implicit Type Casting
Python automatically converts smaller data types to larger ones during operations.
sanfoundry_num = 10 # Integer sanfoundry_float = sanfoundry_num + 5.5 # Integer converted to float print(sanfoundry_float) print(type(sanfoundry_float))
Output:
15.5 <class 'float'>
Explicit Type Casting
Explicit type casting is done using functions like int(), float(), str(), and bool().
- Integer to String:
sanfoundry_num = 100 sanfoundry_str = str(sanfoundry_num) print(sanfoundry_str) # Output: 100
- String to Integer:
sanfoundry_str = "45" sanfoundry_num = int(sanfoundry_str) print(sanfoundry_num + 5) # Output: 50
- Float to Integer:
sanfoundry_rating = 4.9 sanfoundry_num = int(sanfoundry_rating) print(sanfoundry_num) # Output: 4
- List to Tuple:
sanfoundry_subjects = ["Python", "Java", "SQL"] # List sanfoundry_subjects_tuple = tuple(sanfoundry_subjects) # Convert to tuple print(sanfoundry_subjects_tuple) # Output: ('Python', 'Java', 'SQL')
- Convert Any Value to Boolean:
print(bool(0)) # Output: False print(bool(1)) # Output: True print(bool("")) # Output: False (empty string) print(bool("Hello")) # Output: True (non-empty string)
Constants in Python
Constants are usually declared at the beginning of the script or module and follow the naming convention of using all uppercase letters.
SANFOUNDRY_COURSE = "Python Programming" SANFOUNDRY_DURATION = 30 print(SANFOUNDRY_COURSE) print(SANFOUNDRY_DURATION)
Output:
Python Programming
30Use a Separate Module for Constants:
A common approach is to define constants in a separate Python file (constants.py) and import them when needed. For Example:
constants.py
SANFOUNDRY_URL = "https://www.sanfoundry.com" MAX_ATTEMPTS = 5
main.py
import sanfoundry_constants print(sanfoundry_constants.SANFOUNDRY_URL) # Output: https://www.sanfoundry.com
Deleting a Variable in Python
In Python, variables can be deleted using the del keyword. This removes the variable from memory and makes it inaccessible.
sanfoundry_course = "Python" print(sanfoundry_course) del sanfoundry_course # Delete the variable # print(sanfoundry_course) # This will raise an error
Output:
Python
If you try to print the variable after deletion, it will raise:
NameError: name 'sanfoundry_course' is not defined
Deleting Multiple Variables
Multiple variables can be deleted using del in a single line.
sanfoundry_subject1 = "Java" sanfoundry_subject2 = "SQL" del sanfoundry_subject1, sanfoundry_subject2 # print(sanfoundry_subject1) # Will raise NameError
Deleting Items from a List or Dictionary
You can also delete elements from lists and dictionaries using del.
sanfoundry_topics = ["Python", "Java", "SQL"] del sanfoundry_topics[1] # Delete "Java" print(sanfoundry_topics)
Output:
['Python', 'SQL']
Scope of a Variable in Python
In Python, the scope of a variable refers to the region where the variable is accessible. Python has four types of scopes: Local, Enclosing, Global, and Built-in (LEGB Rule).
1. Local Scope
A variable declared inside a function is only accessible within that function.
def sanfoundry_course(): course = "Python" # Local variable print(course) sanfoundry_course() # print(course) # Will raise NameError
Output:
Python
2. Enclosing Scope
A variable declared in an outer function is accessible to the inner (nested) function.
def outer(): sanfoundry_topic = "Java" def inner(): print(sanfoundry_topic) # Accessing outer variable inner() outer()
Output:
Java
3. Global Scope
A variable declared outside any function is accessible throughout the program.
sanfoundry_subject = "SQL" # Global variable def display(): print(sanfoundry_subject) display() print(sanfoundry_subject)
Output:
SQL SQL
4. Built-in Scope
Python provides many built-in functions and variables that are available by default.
sanfoundry_list = [1, 2, 3, 4] print(len(sanfoundry_list)) # len() is a built-in function
Output:
45. Using Global Keyword
To modify a global variable inside a function, use the global keyword.
sanfoundry_course = "Python" def update_course(): global sanfoundry_course sanfoundry_course = "Java" print(sanfoundry_course) update_course() print(sanfoundry_course)
Output:
Java Java
FAQs on Python Variables
1. What is a variable in Python?
A variable is a name that stores a value, such as numbers, strings, or lists. Python does not require explicit variable declarations.
2. How do you declare a variable in Python?
Python does not require an explicit declaration. A variable is created when a value is assigned to it.
3. Is Python case-sensitive with variables?
Yes, variable names are case-sensitive, meaning “var” and “Var” are considered different variables.
4. How do you check the type of a variable?
Python provides a way to check the type of a variable, which helps in understanding what kind of data it holds.
5. Can Python variables change their type?
Yes, Python allows variables to store values of different types at different times, as it supports dynamic typing.
6. How do you modify a global variable inside a function?
A special keyword is used to indicate that a variable inside a function refers to a globally defined variable, allowing modification.
7. Can an inner function modify a variable from an outer function?
Yes, an inner function can modify a variable from the enclosing function using a specific keyword to indicate its usage.
Key Points to Remember
Here is the list of key points we need to remember about “Python Variables”.
- Python variables don’t need explicit type declarations; they adapt to the assigned value and can change type dynamically.
- Variable names must start with a letter or underscore, can’t use reserved keywords, and are case-sensitive.
- Multiple variables can be assigned values in one line, and the same value can be assigned to multiple variables simultaneously.
- Python supports both implicit and explicit type conversions using functions like int(), float(), str(), and bool().
- Constants are usually written in uppercase and can be stored in a separate module for better organization.
- Variables have different scopes: local (inside functions), enclosing (nested functions), global (outside functions), and built-in (predefined by Python). The global keyword allows modifying global variables inside functions.