Python Variables and Data Types – A Beginner-Friendly Guide

Python Variables and Data Types – A Beginner-Friendly Guide

Understand how to declare variables, follow proper naming rules, and explore Python’s primitive and non-primitive data types. This post also explains the difference between mutable and immutable types, with simple examples for each — helping you build a strong foundation for writing clean, efficient Python code.

1. What is a Variable in Python?

A variable is a name that refers to a value stored in memory. It acts as a container to hold data that can be reused or manipulated throughout a program.
 

2. Rules to Declare a Variable in Python:

  • Must start with a letter (a–z, A–Z) or an underscore (_)
  • Can contain letters, digits, and underscores
  • Cannot start with a digit
  • Are case-sensitive (age and Age are different)
  • Must not be a Python keyword (e.g., class, for)
 
✅ Valid Examples:
 
_name = "John"
user1 = 25{codeBox}
 
❌ Invalid Examples:
 
1user = "invalid"  # starts with digit
for = 5            # 'for' is a keyword{codeBox}
 

3. Mutable vs Immutable Data Types:

  • Immutable: An immutable value is one whose content cannot be changed without creating an entirely new value.
  • Mutable: A mutable value is one that can be changed without creating an entirely new value.
 

4. Primitive Data Types:

A primitive type is predefined by the programming language and cannot be broken down into simpler structures.

1. int (Immutable): stores integer numbers like 10, -3, 0
x = 10
print(type(x))
<class 'int'>{codeBox}
 
2. float (Immutable): stores decimal numbers like 10.3, -3.1, 0.1
x = 0.1
print(type(x))
<class 'float'>{codeBox}
 
3. bool (Immutable): stores boolean values True/False
x = True
print(type(x))
<class 'bool'>{codeBox}
 
4. str (Immutable): stores sequence of characters like 'hello world!'
x = 'Hello World!'
print(type(x))
<class 'str'>{codeBox}
 
5. NoneType (Immutable): Represents “no value”
x = None
print(type(x))
<class 'NoneType'>{codeBox}
 

5. Non-Primitive Data Types:

A non-primitive data type is one that is derived from Primitive data types and these data types are not actually defined by the programming language but are created by the programmer. Non-primitive data types are called reference types because they refer to objects.

1. list (Mutable): Stores Ordered and mutable collection of data that allows duplicates
x = [1, "Hello", True, 2, None]
print(type(x))
<class 'list'>{codeBox}
 
2. tuple (Immutable): Stores Ordered and read-only collection of data that allows duplicates
x = (1, "Hello", True, 2, None)
print(type(x))
<class 'tuple'>{codeBox}
 
3. set(Mutable): Stores Unordered and mutable collection of data that does not allow duplicates
x = {1,2,3,4,5}
print(type(x))
<class 'set'>{codeBox}
 
4. dict(Mutable): Stores data in Key-value pairs
x = {"name": "John", "age": 25, "phone": "1234567890"}
print(type(x))
<class 'dict'>{codeBox}

 

Post a Comment

Previous Post Next Post