Variables are one of the most fundamental concepts in Python programming. Every Python program, whether it is a simple calculator, a web application, a machine learning model, or a data analytics dashboard, relies on variables to store and manipulate data. Without variables, a program would have no way to remember values, perform calculations, or process user input.
In Data Analytics and Machine Learning, variables are used extensively to store datasets, customer information, sales figures, prediction results, statistical values, and model parameters. Understanding how variables work is the first step toward writing efficient Python programs.
Unlike many traditional programming languages, Python makes working with variables simple because you do not need to declare the data type explicitly. Python automatically determines the type of data being stored, making it one of the most beginner-friendly programming languages.
In this lesson, you will learn what variables are, how Python stores values in memory, different ways of creating variables, multiple assignment, dynamic typing, and the best practices for naming variables. By the end of this lesson, you will have a strong understanding of how Python manages data internally and how to write clean, readable, and professional code.
After completing this lesson, you will be able to:
A variable is a named storage location that holds a value in a computer’s memory. Instead of remembering the actual value, programmers use the variable name to access, modify, or display the stored information.
You can think of a variable as a labeled container. The label represents the variable name, while the container stores the actual data. Whenever the program needs that data, it refers to the label rather than the value itself.
For example, instead of repeatedly writing the number 50000 throughout your program, you can store it in a variable called salary. If the salary changes later, you only need to update the variable once instead of modifying every occurrence.
salary = 50000
print(salary)
Output:
50000
Here, salary is the variable name, while 50000 is the value stored inside it.
Imagine a library where every book is placed on a shelf with a unique label. Instead of searching through every book, you simply look for the label to find the required book. Variables work in a similar way. The variable name acts as the label, while the stored value is the book.
| Real Life | Python |
|---|---|
| Storage Box | Variable |
| Label on the Box | Variable Name |
| Items Inside the Box | Stored Value |
| Opening the Box | Accessing the Variable |
Variables allow programs to store information that can be reused throughout execution. Without variables, every calculation would require hardcoded values, making programs difficult to update and maintain.
Variables provide flexibility by allowing data to change dynamically while the program is running.
print(25000 + 5000)
print(25000 + 5000)
print(25000 + 5000)
If the salary changes, every occurrence must be updated manually.
salary = 25000
bonus = 5000
print(salary + bonus)
print(salary + bonus)
print(salary + bonus)
Now, changing the value of salary or bonus automatically updates every calculation.
When you assign a value to a variable, Python stores that value somewhere in the computer’s memory. The variable does not contain the actual data; instead, it references the memory location where the data is stored.
This memory management is handled automatically by Python, so developers do not need to allocate or free memory manually.
age = 22
In this example:
22 is stored in memory.age refers to that stored value.age is used, Python retrieves the value from memory.Variable Name Memory Stored Value
age -------------> 0x102A 22
The memory address shown above is only a conceptual illustration. Python manages actual memory locations internally, and programmers usually do not need to know the exact address.
Every object created in Python has three important characteristics:
For example:
city = "Dehradun"
| Property | Value |
|---|---|
| Variable Name | city |
| Data Type | String |
| Stored Value | Dehradun |
| Memory | Managed Automatically by Python |
Understanding this concept helps explain why variables can be reassigned to different values and even different data types during program execution.
Creating a variable in Python is simple. Unlike languages such as C, C++, or Java, Python does not require you to specify the data type before creating a variable. You simply assign a value using the assignment operator (=).
name = "Rahul"
age = 21
percentage = 89.5
Python automatically determines the appropriate data type based on the assigned value.
student_name = "Anjali"
roll_number = 101
fees_paid = True
height = 5.6
Each variable stores a different type of information, yet the syntax remains the same.
The assignment operator (=) assigns the value on the right-hand side to the variable on the left-hand side.
price = 150
discount = 20
final_price = price - discount
print(final_price)
Output:
130
The assignment operator should not be confused with the equality operator (==), which is used for comparison.
Python allows you to assign values to multiple variables in a single statement. This feature makes code concise and readable.
name, age, city = "Amit", 24, "Delhi"
print(name)
print(age)
print(city)
Output:
Amit
24
Delhi
The number of variables must match the number of assigned values. Otherwise, Python raises a ValueError.
x, y = 10, 20, 30
This results in an error because there are more values than variables.
You can also assign a single value to multiple variables in one statement.
x = y = z = 100
print(x)
print(y)
print(z)
Output:
100
100
100
This technique is useful when multiple variables should start with the same initial value.
One of Python’s most powerful features is dynamic typing. In Python, a variable is not permanently associated with a single data type. Instead, the type depends on the value currently assigned to the variable.
This means you can reassign the same variable to different types of data without declaring its type explicitly.
value = 100
print(value)
value = "Python"
print(value)
value = 98.5
print(value)
Output:
100
Python
98.5
Here, the variable value changes from an integer to a string and then to a floating-point number. Python automatically updates the variable’s type based on the new value.
Dynamic typing makes Python highly flexible and easy to use, especially for rapid development, scripting, automation, and data analysis. However, developers should use meaningful variable names and avoid changing a variable’s type unnecessarily, as doing so can make programs harder to understand and debug.
In this section, you learned the fundamentals of Python variables, including what variables are, why they are important, how Python stores data in memory, and how to create and assign variables. You explored single assignment, multiple assignment, assigning the same value to multiple variables, and Python’s dynamic typing system. These concepts form the foundation for working with all types of data in Python. In the next chunk, you will explore Python’s built-in data types, including integers, floating-point numbers, strings, booleans, None, and learn how to inspect data types using the type(), id(), and isinstance() functions.
Every value stored in a Python variable belongs to a particular category known as a data type. A data type tells Python what kind of value is being stored and what operations can be performed on it. For example, numbers can be added or multiplied, while strings can be concatenated or searched. Choosing the correct data type makes programs more efficient, readable, and reliable.
Python is a dynamically typed language, which means you do not need to specify the data type while creating a variable. Python automatically determines the data type based on the assigned value.
age = 25
name = "Rahul"
salary = 55000.75
is_student = True
In the above example, Python automatically identifies the data types of all four variables.
Python provides several built-in data types. They can be grouped into the following categories.
| Category | Data Types |
|---|---|
| Numeric | int, float, complex |
| Text | str |
| Boolean | bool |
| Null | NoneType |
| Collection | list, tuple, set, dictionary |
In this chunk, we will focus on the numeric, text, boolean, and None data types. Collection data types will be covered in the next chunk.
An integer is a whole number that does not contain a decimal point. Integers can be positive, negative, or zero.
age = 22
temperature = -5
students = 150
balance = 0
Integers are commonly used to represent quantities such as student IDs, ages, product counts, years, and inventory levels.
a = 20
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a // b)
Output:
25
15
100
4
A float represents numbers containing a decimal point. Floats are commonly used for measurements, percentages, scientific calculations, and financial data.
height = 5.8
price = 299.99
interest_rate = 7.5
average_marks = 84.6
price = 99.95
tax = 18.50
total = price + tax
print(total)
Output:
118.45
Because of the way computers represent decimal numbers internally, floating-point calculations may sometimes produce small precision errors. Python provides additional modules such as decimal when higher precision is required.
A complex number consists of two parts:
jComplex numbers are mainly used in scientific computing, engineering, electronics, signal processing, and mathematics.
number = 3 + 4j
print(number)
Output:
(3+4j)
You can access the real and imaginary parts separately.
number = 3 + 4j
print(number.real)
print(number.imag)
Output:
3.0
4.0
A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Strings are used to store textual information such as names, addresses, emails, product descriptions, and messages.
name = "Amit"
city = 'Dehradun'
course = """Data Analytics"""
All three methods create string objects.
first_name = "Rahul"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(full_name)
Output:
Rahul Sharma
print("Python " * 3)
Output:
Python Python Python
language = "Python"
print(language[0])
print(language[3])
Output:
P
h
| Function | Description |
|---|---|
| len() | Returns string length. |
| upper() | Converts to uppercase. |
| lower() | Converts to lowercase. |
| replace() | Replaces text. |
| strip() | Removes leading and trailing spaces. |
| split() | Splits a string into a list. |
course = "Python Programming"
print(len(course))
print(course.upper())
print(course.lower())
A Boolean data type represents one of two possible values:
TrueFalseBoolean values are mainly used in conditions, comparisons, loops, and decision-making.
is_logged_in = True
has_paid_fee = False
print(is_logged_in)
print(has_paid_fee)
age = 18
print(age >= 18)
print(age < 18)
Output:
True
False
Booleans are widely used in Data Analytics for filtering records and applying conditions.
Sometimes a variable has no value assigned yet. Python represents this situation using the special value None.
The data type of None is called NoneType.
result = None
print(result)
Output:
None
None is commonly used as a placeholder until a value becomes available.
student_name = None
if student_name is None:
print("No student assigned.")
The type() function returns the data type of any Python object. It is one of the most frequently used functions while learning Python and debugging programs.
age = 22
price = 99.95
name = "Python"
status = True
print(type(age))
print(type(price))
print(type(name))
print(type(status))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
Every object created in Python has a unique identity during its lifetime. The id() function returns an integer that represents the identity of an object. In CPython, this value is generally related to the object's memory address, but you should think of it as a unique identifier rather than relying on it being a physical memory address.
name = "Python"
print(id(name))
The exact number displayed will vary from one computer and one program execution to another.
The isinstance() function checks whether an object belongs to a specified data type or class. Unlike comparing the result of type(), isinstance() also works correctly with inheritance and is generally preferred in professional Python code.
isinstance(object, class_or_type)
age = 25
print(isinstance(age, int))
print(isinstance(age, float))
Output:
True
False
course = "Python"
print(isinstance(course, str))
Output:
True
The isinstance() function is especially useful when writing reusable functions that need to validate input before processing it.
Suppose you are analyzing student data. Different pieces of information require different data types.
student_name = "Priya"
age = 20
percentage = 91.8
is_placed = True
project = None
Here:
student_name is a string.age is an integer.percentage is a float.is_placed is a Boolean.project currently has no value, so it is None.Using the appropriate data type makes programs easier to understand and reduces the likelihood of errors.
In this section, you learned about Python's fundamental built-in data types, including integers, floating-point numbers, complex numbers, strings, Booleans, and NoneType. You also learned how to inspect objects using the type(), id(), and isinstance() functions. These concepts are essential because every value in Python has a type that determines how it can be stored and manipulated. In the next chunk, you will explore Python's collection data types—lists, tuples, sets, and dictionaries—and understand the difference between mutable and immutable objects.
So far, you have learned how Python stores individual values such as integers, floating-point numbers, strings, Booleans, and None. However, real-world applications often require storing multiple related values together. For example, a Data Analytics project may need to store thousands of customer names, product prices, sales records, or survey responses.
Python provides several built-in collection data types to store multiple values efficiently. Each collection has its own characteristics and is designed for different purposes.
The four primary collection data types in Python are:
A list is an ordered collection of items. Lists are one of the most commonly used data structures in Python because they are flexible and easy to work with.
Lists can store multiple values of different data types and allow duplicate values.
[].students = ["Rahul", "Anjali", "Amit", "Priya"]
print(students)
Output:
['Rahul', 'Anjali', 'Amit', 'Priya']
employee = ["Rahul", 25, 55000.50, True]
print(employee)
A list can contain strings, integers, floating-point numbers, Booleans, and even other lists.
List elements are accessed using an index. Python uses zero-based indexing, meaning the first element has an index of 0.
cities = ["Delhi", "Mumbai", "Dehradun", "Jaipur"]
print(cities[0])
print(cities[2])
Output:
Delhi
Dehradun
cities = ["Delhi", "Mumbai", "Dehradun"]
cities[1] = "Chennai"
print(cities)
Output:
['Delhi', 'Chennai', 'Dehradun']
This demonstrates that lists are mutable because their elements can be changed after creation.
| Method | Description |
|---|---|
| append() | Adds an item to the end of the list. |
| insert() | Inserts an item at a specified position. |
| remove() | Removes the first matching item. |
| pop() | Removes and returns an item. |
| sort() | Sorts the list in ascending order. |
| reverse() | Reverses the list. |
| len() | Returns the number of items. |
A tuple is an ordered collection similar to a list, but unlike a list, a tuple cannot be modified after it is created. Therefore, tuples are called immutable.
Tuples are useful when the stored data should remain unchanged, such as dates, geographic coordinates, or configuration values.
().colors = ("Red", "Green", "Blue")
print(colors)
colors = ("Red", "Green", "Blue")
print(colors[1])
Output:
Green
colors = ("Red", "Green", "Blue")
colors[0] = "Black"
The above code produces a TypeError because tuples are immutable.
A set is an unordered collection of unique elements. Sets automatically remove duplicate values, making them useful for eliminating repeated items.
{}.numbers = {10, 20, 30, 40}
print(numbers)
numbers = {10, 20, 20, 30, 30, 40}
print(numbers)
Output:
{10, 20, 30, 40}
numbers = {10, 20, 30}
numbers.add(40)
print(numbers)
| Method | Description |
|---|---|
| add() | Adds an element. |
| remove() | Removes an element. |
| discard() | Removes an element if it exists. |
| union() | Returns the union of two sets. |
| intersection() | Returns common elements. |
| difference() | Returns elements present in the first set only. |
A dictionary stores data as key-value pairs. Each key is unique and is associated with a corresponding value.
Dictionaries are widely used in Data Analytics because they efficiently represent structured information such as student records, customer details, product information, and JSON data.
{}.student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
print(student)
print(student["name"])
print(student["course"])
Output:
Rahul
Python
student["city"] = "Dehradun"
print(student)
student["age"] = 23
print(student)
| Method | Description |
|---|---|
| keys() | Returns all keys. |
| values() | Returns all values. |
| items() | Returns key-value pairs. |
| get() | Returns the value for a key. |
| update() | Updates multiple key-value pairs. |
| pop() | Removes a key-value pair. |
One of the most important concepts in Python is understanding whether an object is mutable or immutable.
A mutable object can be changed after it is created, whereas an immutable object cannot be modified once it has been created.
| Mutable | Immutable |
|---|---|
| List | Tuple |
| Dictionary | String |
| Set | Integer |
| Bytearray | Float |
| Boolean |
marks = [70, 80, 90]
marks[0] = 75
print(marks)
Output:
[75, 80, 90]
name = "Python"
name[0] = "J"
This produces a TypeError because strings are immutable.
Suppose you are building a student analytics application.
student = {
"name": "Anjali",
"age": 21,
"marks": [82, 91, 88],
"subjects": ("Python", "SQL", "Power BI"),
"skills": {"Python", "Excel", "SQL"}
}
print(student)
In this example:
| If You Need... | Use |
|---|---|
| An ordered, editable collection | List |
| An ordered collection that should not change | Tuple |
| Unique values without duplicates | Set |
| Key-value mapping | Dictionary |
In this section, you explored Python's four primary collection data types: lists, tuples, sets, and dictionaries. You learned their characteristics, how to create and access them, common methods, and when each should be used. You also understood the difference between mutable and immutable objects, an essential concept for writing efficient Python programs. In the final chunk of this lesson, you will learn about type conversion, naming best practices, common mistakes, memory optimization basics, followed by the lesson summary, FAQs, MCQs, coding exercises, interview questions, a mini project, and the "What's Next?" section to complete the lesson.
In real-world programming, data often comes from different sources such as user input, files, databases, APIs, or sensors. These sources may provide data in formats that are not immediately suitable for calculations or processing. For example, user input is usually received as text, even when the user enters a number. To work with such data correctly, Python provides type conversion.
Type conversion is the process of changing a value from one data type to another. Python supports two types of type conversion:
Implicit type conversion, also known as automatic type conversion, occurs when Python automatically converts one data type into another without requiring any action from the programmer.
This usually happens when different numeric data types are used together in an expression.
marks = 85
percentage = 2.5
result = marks + percentage
print(result)
print(type(result))
Output:
87.5
<class 'float'>
Although marks is an integer, Python automatically converts it to a floating-point number before performing the addition.
a = 20
b = 3.5
print(a * b)
Output:
70.0
This automatic conversion helps prevent loss of information during mathematical operations.
Explicit type conversion, also called type casting, occurs when the programmer manually converts one data type into another using Python's built-in conversion functions.
Some of the most commonly used conversion functions are:
int()float()str()bool()list()tuple()set()dict()The int() function converts compatible values into integers.
price = 99.95
print(int(price))
Output:
99
The decimal portion is discarded rather than rounded.
age = "25"
print(int(age))
Output:
25
The float() function converts integers and numeric strings into floating-point numbers.
marks = 90
print(float(marks))
Output:
90.0
salary = "45000.75"
print(float(salary))
The str() function converts almost any Python object into a string.
age = 25
print(str(age))
Output:
'25'
This conversion is useful when displaying numbers inside messages.
marks = 95
print("Marks: " + str(marks))
The bool() function converts values into either True or False.
| Value | Boolean Result |
|---|---|
| 0 | False |
| 1 | True |
| "" (Empty String) | False |
| "Python" | True |
| [] | False |
| [1,2] | True |
| None | False |
print(bool(0))
print(bool(100))
print(bool(""))
Output:
False
True
False
numbers = [10, 20, 30]
result = tuple(numbers)
print(result)
colors = ("Red", "Green", "Blue")
print(list(colors))
numbers = [1, 2, 2, 3, 4]
print(set(numbers))
Duplicate values are automatically removed.
Not every value can be converted successfully. If Python cannot perform the requested conversion, it raises an exception.
age = "Twenty"
print(int(age))
Output:
ValueError: invalid literal for int()
Always ensure that the value is compatible with the target data type before converting it.
Good variable names make programs easier to read and maintain. Choose descriptive names that clearly indicate the purpose of the stored value.
student_name
total_sales
average_salary
customer_count
monthly_profit
a
x
temp
abc
data1
= with ==.Python automatically manages memory through its built-in memory management system and garbage collector. As a programmer, you usually do not need to allocate or free memory manually.
However, writing efficient code still helps reduce memory usage.
student_name = "Rahul"
age = int("22")
marks = float("91.5")
is_placed = bool(1)
student = {
"name": student_name,
"age": age,
"marks": marks,
"placed": is_placed
}
print(student)
This example combines variables, dictionaries, type conversion, and Boolean values to represent a simple student record.
In this lesson, you learned how Python stores and manages data using variables and built-in data types. You explored variable creation, assignment, multiple assignment, dynamic typing, numeric types, strings, Booleans, NoneType, lists, tuples, sets, dictionaries, mutable and immutable objects, and type conversion. You also learned how to inspect object types using type(), id(), and isinstance(), along with best practices for naming variables and writing efficient Python code. These concepts provide the foundation for all future Python programming and are essential for Data Analytics, Machine Learning, Automation, and Software Development.
type()id()isinstance().snake_case.type(), id(), and isinstance() functions?Create a Python program named student_profile.py that:
type().Congratulations! You have completed the Python Variables and Data Types lesson. In the next lesson, you will learn Python Operators, including arithmetic, comparison, logical, assignment, bitwise, identity, and membership operators. You will also explore operator precedence, associativity, and practical examples used in Data Analytics and Machine Learning.
In real-world programming, data often comes from different sources such as user input, files, databases, APIs, or sensors. These sources may provide data in formats that are not immediately suitable for calculations or processing. For example, user input is usually received as text, even when the user enters a number. To work with such data correctly, Python provides type conversion.
Type conversion is the process of changing a value from one data type to another. Python supports two types of type conversion:
Implicit type conversion, also known as automatic type conversion, occurs when Python automatically converts one data type into another without requiring any action from the programmer.
This usually happens when different numeric data types are used together in an expression.
marks = 85
percentage = 2.5
result = marks + percentage
print(result)
print(type(result))
Output:
87.5
<class 'float'>
Although marks is an integer, Python automatically converts it to a floating-point number before performing the addition.
a = 20
b = 3.5
print(a * b)
Output:
70.0
This automatic conversion helps prevent loss of information during mathematical operations.
Explicit type conversion, also called type casting, occurs when the programmer manually converts one data type into another using Python's built-in conversion functions.
Some of the most commonly used conversion functions are:
int()float()str()bool()list()tuple()set()dict()The int() function converts compatible values into integers.
price = 99.95
print(int(price))
Output:
99
The decimal portion is discarded rather than rounded.
age = "25"
print(int(age))
Output:
25
The float() function converts integers and numeric strings into floating-point numbers.
marks = 90
print(float(marks))
Output:
90.0
salary = "45000.75"
print(float(salary))
The str() function converts almost any Python object into a string.
age = 25
print(str(age))
Output:
'25'
This conversion is useful when displaying numbers inside messages.
marks = 95
print("Marks: " + str(marks))
The bool() function converts values into either True or False.
| Value | Boolean Result |
|---|---|
| 0 | False |
| 1 | True |
| "" (Empty String) | False |
| "Python" | True |
| [] | False |
| [1,2] | True |
| None | False |
print(bool(0))
print(bool(100))
print(bool(""))
Output:
False
True
False
numbers = [10, 20, 30]
result = tuple(numbers)
print(result)
colors = ("Red", "Green", "Blue")
print(list(colors))
numbers = [1, 2, 2, 3, 4]
print(set(numbers))
Duplicate values are automatically removed.
Not every value can be converted successfully. If Python cannot perform the requested conversion, it raises an exception.
age = "Twenty"
print(int(age))
Output:
ValueError: invalid literal for int()
Always ensure that the value is compatible with the target data type before converting it.
Good variable names make programs easier to read and maintain. Choose descriptive names that clearly indicate the purpose of the stored value.
student_name
total_sales
average_salary
customer_count
monthly_profit
a
x
temp
abc
data1
= with ==.Python automatically manages memory through its built-in memory management system and garbage collector. As a programmer, you usually do not need to allocate or free memory manually.
However, writing efficient code still helps reduce memory usage.
student_name = "Rahul"
age = int("22")
marks = float("91.5")
is_placed = bool(1)
student = {
"name": student_name,
"age": age,
"marks": marks,
"placed": is_placed
}
print(student)
This example combines variables, dictionaries, type conversion, and Boolean values to represent a simple student record.
In this lesson, you learned how Python stores and manages data using variables and built-in data types. You explored variable creation, assignment, multiple assignment, dynamic typing, numeric types, strings, Booleans, NoneType, lists, tuples, sets, dictionaries, mutable and immutable objects, and type conversion. You also learned how to inspect object types using type(), id(), and isinstance(), along with best practices for naming variables and writing efficient Python code. These concepts provide the foundation for all future Python programming and are essential for Data Analytics, Machine Learning, Automation, and Software Development.
type()id()isinstance().snake_case.type(), id(), and isinstance() functions?Create a Python program named student_profile.py that:
type().Congratulations! You have completed the Python Variables and Data Types lesson. In the next lesson, you will learn Python Operators, including arithmetic, comparison, logical, assignment, bitwise, identity, and membership operators. You will also explore operator precedence, associativity, and practical examples used in Data Analytics and Machine Learning.