1. Introduction
In Python, variables are used to store data, and data types define the type of data that a variable can hold. Python is a dynamically typed language, which means you do not need to declare the type of a variable explicitly.
2. Variables in Python
2.1 Definition
A variable is a name given to a memory location that stores a value.
2.2 Creating Variables
In Python, variables are created when a value is assigned to them using the assignment operator (=).
x = 10
name = "Python"
price = 99.5
2.3 Rules for Naming Variables
- Must start with a letter or underscore (
_)
- Cannot start with a digit
- Can contain letters, digits, and underscores
- Cannot be a keyword
- Case-sensitive (
name and Name are different)
2.4 Examples
age = 20
student_name = "Rahul"
_total = 100
2.5 Multiple Assignment
a, b, c = 1, 2, 3
2.6 Assigning Same Value
x = y = z = 10
2.7 Dynamic Typing
x = 10
x = "Hello"
Explanation
- The same variable can store different types of data.
3. Data Types in Python
3.1 Definition
A data type specifies the type of value a variable holds.
4. Basic Data Types
4.1 Numeric Data Types
1. Integer (int)
- Whole numbers (positive or negative)
x = 10
2. Float (float)
y = 3.14
3. Complex (complex)
- Numbers with real and imaginary parts
z = 2 + 3j
4.2 Boolean Data Type (bool)
a = True
b = False
4.3 String Data Type (str)
name = "Python"
message = 'Hello'
5. Collection Data Types
5.1 List (list)
- Ordered, mutable collection
numbers = [1, 2, 3, 4]
5.2 Tuple (tuple)
- Ordered, immutable collection
data = (1, 2, 3)
5.3 Set (set)
- Unordered collection of unique elements
values = {1, 2, 3}
5.4 Dictionary (dict)
- Collection of key-value pairs
student = {"name": "Rahul", "age": 20}
6. Checking Data Type
Use the type() function:
x = 10
print(type(x))
Output
<class 'int'>
7. Type Conversion
7.1 Implicit Conversion
x = 5
y = 2.5
result = x + y
print(result)
7.2 Explicit Conversion
x = "10"
y = int(x)
print(y)
8. Summary
- Variables are used to store data in Python.
- Python is dynamically typed, so no need to declare data types.
- Data types define the type of value stored in variables.
- Common types include int, float, str, bool, list, tuple, set, and dictionary.
- The
type() function is used to check the data type.
- Type conversion can be implicit or explicit.