Understanding Python Variables and Data Types
Understanding Python Variables and Data Types
In Python, variables are used to store data, and data types define the type of data a variable can hold.
1. Variables in Python
A variable is a name given to a memory location where data is stored. In Python, variables are dynamically typed, meaning you don’t need to declare their type before using them.
Declaring and Assigning Variables
python
Copy
Edit
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_valid = True # Boolean
Python automatically determines the type based on the assigned value.
Variable Naming Rules
Must start with a letter (a-z, A-Z) or underscore (_).
Cannot start with a digit (e.g., 1var is invalid).
Can contain letters, digits, and underscores (e.g., my_variable is valid).
Case-sensitive (Age and age are different).
Cannot be a Python keyword (e.g., def, class).
2. Python Data Types
Python has several built-in data types:
a) Numeric Types
Integer (int) – Whole numbers
python
Copy
Edit
age = 25 # int
Float (float) – Decimal numbers
python
Copy
Edit
price = 99.99 # float
Complex (complex) – Numbers with a real and imaginary part
python
Copy
Edit
num = 3 + 5j # complex
b) Sequence Types
String (str) – Text data enclosed in quotes
python
Copy
Edit
message = "Hello, World!"
List (list) – Ordered, mutable collection
python
Copy
Edit
numbers = [1, 2, 3, 4, 5]
Tuple (tuple) – Ordered, immutable collection
python
Copy
Edit
coordinates = (10.5, 20.3)
c) Set Types
Set (set) – Unordered, unique items
python
Copy
Edit
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
Frozen Set (frozenset) – Immutable set
python
Copy
Edit
frozen_set = frozenset([1, 2, 3])
d) Dictionary Type
Dictionary (dict) – Key-value pairs
python
Copy
Edit
person = {"name": "John", "age": 30}
e) Boolean Type
Boolean (bool) – True or False values
python
Copy
Edit
is_active = True
f) None Type
NoneType – Represents absence of value
python
Copy
Edit
value = None
3. Checking Data Types
Use type() to check a variable’s data type:
python
Copy
Edit
x = 10
print(type(x)) # <class 'int'>
4. Type Conversion
Python allows converting one data type to another.
a) Implicit Type Conversion (Automatic)
Python automatically converts a smaller data type to a larger one.
python
Copy
Edit
x = 10 # int
y = 2.5 # float
result = x + y # float
print(type(result)) # <class 'float'>
b) Explicit Type Conversion (Casting)
Manually convert types using int(), float(), str(), etc.
python
Copy
Edit
a = "100"
b = int(a) # Convert string to integer
print(type(b)) # <class 'int'>
Conclusion
Understanding variables and data types is fundamental in Python programming. With Python’s dynamic
typing, variables can hold different data types, making coding flexible and powerful.
Read More
Key Concepts Every Cybersecurity Student Must Know
What are the best Python scripts you've ever written?
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment