πŸ”Ή What is a Variable in Python?

A variable in Python is a name that stores a value. Variables allow you to store and manipulate data in your program.

βœ… Example of a variable:

name = "Alice"  # String variable
age = 25        # Integer variable
height = 5.7    # Float variable

Here, name, age, and height are variables, and "Alice", 25, and 5.7 are their values.


πŸ”Ή Rules for Naming Variables

  1. Must start with a letter (A-Z or a-z) or an underscore (_)
    • βœ… my_var, _name, Age
    • ❌ 2name (Cannot start with a digit)
  2. Can contain letters, digits, and underscores (_)
    • βœ… user_123, name2, first_name
    • ❌ user@name, first-name (No special characters)
  3. Cannot use Python reserved keywords
    • ❌ if = 10, class = "Math"
  4. Case-sensitive (name β‰  Name)
    Name = "Alice"
    name = "Bob"
    print(Name)  # Output: Alice
    print(name)  # Output: Bob
    

πŸ”Ή Data Types in Python

Python has several built-in data types that determine the type of a variable.

πŸ“Œ Numeric Data Types

Data Type Example Description
int x = 10 Whole numbers (Positive/Negative)
float y = 5.75 Decimal numbers
complex z = 3 + 4j Complex numbers
x = 100      # int
y = 12.5     # float
z = 2 + 3j   # complex

Check the type of a variable:

print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'float'>
print(type(z))  # Output: <class 'complex'>

πŸ“Œ String Data Type (str)

A sequence of characters enclosed in single or double quotes.

message = "Hello, Python!"
name = 'Alice'

print(type(message))  # Output: <class 'str'>

βœ… Multi-line strings use triple quotes (''' or """):

paragraph = """This is
a multi-line
string."""

πŸ“Œ Boolean Data Type (bool)

Boolean variables hold True or False values.

is_active = True
is_deleted = False

print(type(is_active))  # Output: <class 'bool'>

Booleans are often used in conditions:

if is_active:
    print("User is active")

πŸ“Œ Sequence Data Types

Type Example Description
list [1, 2, 3] Ordered, mutable collection
tuple (1, 2, 3) Ordered, immutable collection
range range(5) Sequence of numbers

Lists (list)

A list is a mutable (changeable) collection of elements.

numbers = [10, 20, 30, 40]
numbers.append(50)  # Adds an element
print(numbers)  # Output: [10, 20, 30, 40, 50]

Tuples (tuple)

A tuple is an immutable (unchangeable) collection.

coordinates = (4, 5)
# coordinates[0] = 10  ❌ Error (tuples cannot be changed)

πŸ“Œ Set Data Type (set)

A set is an unordered collection of unique elements.

my_set = {1, 2, 3, 3, 4}
print(my_set)  # Output: {1, 2, 3, 4} (duplicates removed)

πŸ“Œ Dictionary Data Type (dict)

A dictionary stores data in key-value pairs.

student = {"name": "Alice", "age": 25, "grade": "A"}
print(student["name"])  # Output: Alice

πŸ”Ή Dynamic Typing in Python

Python allows dynamic typing, meaning you don’t need to declare a variable type explicitly.

x = 10       # int
x = "hello"  # Now x is a str

πŸ”Ή Type Casting (Converting Data Types)

Python allows explicit type conversion.

num = "100"
num = int(num)  # Convert str to int
print(type(num))  # Output: <class 'int'>

Other conversions:

float_num = float("10.5")  # str β†’ float
str_num = str(100)         # int β†’ str
list_from_tuple = list((1, 2, 3))  # tuple β†’ list

βœ… Summary

Data Type Example Mutable?
int x = 10 ❌ No
float y = 10.5 ❌ No
str "Hello" ❌ No
bool True / False ❌ No
list [1, 2, 3] βœ… Yes
tuple (1, 2, 3) ❌ No
set {1, 2, 3} βœ… Yes
dict {"name": "Alice"} βœ… Yes

Python variables do not require explicit declaration and can hold different types at runtime.

Would you like some real-world examples of using these data types? 😊

 

 

πŸ”Ή What is a frozenset in Python?

A frozenset is an immutable version of a set. This means that, unlike normal sets, a frozenset cannot be modified (no adding or removing elements) after creation.

βœ… Key Characteristics of frozenset:

  • Unordered (like set)
  • Immutable (cannot be changed after creation)
  • Does not allow duplicate elements

πŸ”Ή Creating a frozenset

You can create a frozenset using the frozenset() function.

Example 1: Creating a frozenset

my_frozen_set = frozenset([1, 2, 3, 4, 2, 3])
print(my_frozen_set)  # Output: frozenset({1, 2, 3, 4})

βœ… Duplicates are automatically removed, just like in a normal set.


πŸ”Ή Difference Between set and frozenset

Feature set frozenset
Mutable? βœ… Yes ❌ No
Ordered? ❌ No ❌ No
Allows Duplicates? ❌ No ❌ No
Can Add/Remove Elements? βœ… Yes (add(), remove()) ❌ No
Hashable? ❌ No βœ… Yes (can be used as a dictionary key)

πŸ”Ή Operations on frozenset

Although frozenset is immutable, you can still perform set operations like union, intersection, and difference.

Example 2: Using frozenset in Set Operations

A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

# Union
print(A | B)  # Output: frozenset({1, 2, 3, 4, 5, 6})

# Intersection
print(A & B)  # Output: frozenset({3, 4})

# Difference
print(A - B)  # Output: frozenset({1, 2})
print(B - A)  # Output: frozenset({5, 6})

# Symmetric Difference
print(A ^ B)  # Output: frozenset({1, 2, 5, 6})

πŸ”Ή Why Use frozenset?

  • Used as dictionary keys (since it’s immutable)
  • Used in sets of sets (since normal sets are unhashable)
  • Prevents accidental modification

Example 3: Using frozenset as a Dictionary Key

data = {frozenset([1, 2, 3]): "Group A", frozenset([4, 5]): "Group B"}
print(data)  
# Output: {frozenset({1, 2, 3}): 'Group A', frozenset({4, 5}): 'Group B'}

βœ… Normal sets cannot be used as dictionary keys, but frozenset can.


βœ… Summary

  • frozenset is an immutable version of set.
  • It supports set operations but does not allow modification (add(), remove() don’t work).
  • It can be used as a dictionary key or inside another set.

Would you like a real-world example of using frozenset in data processing? 😊


Leave a Reply

Your email address will not be published. Required fields are marked *