02

Day 2: Variables and Data Types

Chapter 2 • Beginner

25 min

Variables are like labeled boxes where you store information. Think of them as containers that hold different types of data.

What are Variables?

Variables are containers for storing data values. In Python, you create a variable simply by giving it a name and assigning a value to it.

Think of variables like labeled boxes in a warehouse. Each box has a name (variable name) and contains something (value).

Understanding Data Types

Python automatically figures out what type of data you're storing. Here are the main types:

Text Type

  • str (string) - Text data like "Hello", "Python", "123"

Numeric Types

  • int (integer) - Whole numbers like 1, 100, -5
  • float (floating point) - Decimal numbers like 3.14, 2.5, -1.2
  • complex - Complex numbers (advanced)

Sequence Types

  • list - Ordered collection of items [1, 2, 3]
  • tuple - Unchangeable ordered collection (1, 2, 3)
  • range - Sequence of numbers range(1, 10)

Mapping Type

  • dict (dictionary) - Key-value pairs {"name": "Alice", "age": 25}

Set Types

  • set - Collection of unique items {1, 2, 3}
  • frozenset - Unchangeable set

Boolean Type

  • bool - True or False values

Binary Types

  • bytes - Binary data
  • bytearray - Mutable binary data
  • memoryview - Memory view object

Variable Naming Rules

When naming variables in Python, follow these rules:

  • Must start with a letter or underscore - name, _age, user1
  • Can contain letters, numbers, and underscores - user_name, age2, total_count
  • Case-sensitive - name and Name are different variables
  • Cannot use reserved keywords - print, if, for, while, etc.
  • Use descriptive names - firstName instead of fn

Good vs Bad Variable Names

Good Names:

  • user_name - Clear and descriptive
  • total_price - Easy to understand
  • student_count - Meaningful

Bad Names:

  • x, y, z - Not descriptive
  • a1, b2, c3 - Unclear purpose
  • print - Reserved keyword

Working with Variables

You can assign values to variables and change them later. Python is dynamic, meaning you can change the type of data a variable holds.

Type Checking

Use the type() function to check what type of data a variable contains. This is helpful for debugging and understanding your code.

Hands-on Examples

Different Data Types

# String variable
name = "Schoolabe"
print(f"Name: {name}, Type: {type(name)}")

# Integer variable
age = 25
print(f"Age: {age}, Type: {type(age)}")

# Float variable
height = 5.6
print(f"Height: {height}, Type: {type(height)}")

# Boolean variable
is_student = True
print(f"Is Student: {is_student}, Type: {type(is_student)}")

# Changing variable type
age = "twenty-five"  # Now it's a string
print(f"Age after change: {age}, Type: {type(age)}")

Python automatically assigns data types based on the value. You can change the type of a variable by assigning a different type of value.