Chapter: Variables and Data Types in Python


1. Variables in Python

1.1 What Are Variables?

Variables are names used to store data values. Think of a variable as a container for data. You can assign, modify, and use variables throughout your program.

1.2 Variable Naming Rules

Here are the official rules for naming variables:

  1. Variable names can only contain letters, numbers, and underscores (_).

  2. They must not start with a number.

  3. Variable names are case-sensitive (age and Age are different variables).

  4. Reserved words (like if, else, while, etc.) cannot be used as variable names.

1.3 Good Practices for Naming Variables

  • Use descriptive names (e.g., user_name instead of x).

  • Use snake_case for variables (e.g., first_name).

  • Keep names consistent.

1.4 Assigning Values to Variables

You can assign values to variables using the = operator:

Multiple Assignments

You can assign multiple variables in one line:

Reassigning Variables

Variables in Python are dynamic, meaning their value and type can be reassigned.


2. Data Types in Python

Python has several built-in data types. These are broadly categorized into numeric, text, sequence, set, mapping, and boolean types.

2.1 Numeric Data Types

Integer (int)

  • Whole numbers, positive or negative, with no decimal points.

  • Unlimited precision (can store very large numbers).

Example:

Float (float)

  • Numbers with decimal points or in exponential form.

Example:

Complex (complex)

  • Numbers with a real and imaginary part.

Example:

Numeric Type
Example
Notes

int

42, -3

No decimal places.

float

3.14, -2.71

Has decimals.

complex

3 + 4j

Imaginary numbers.


2.2 Text Data Type

String (str)

  • A sequence of characters enclosed in single, double, or triple quotes.

Examples:

Tricks & Precautions:

  • Strings are immutable. You can’t change their contents directly.

  • Use escape sequences (, , etc.) to include special characters.

Common String Operations:

Operation
Example
Result

Concatenation

"Hello " + "World"

"Hello World"

Repetition

"A" * 5

"AAAAA"

Slicing

"Python"[0:3]

"Pyt"

Length

len("Hello")

5


2.3 Boolean Data Type

Boolean (bool)

  • Represents True or False.

Example:

Booleans are often used in conditions:


2.4 Sequence Data Types

List

  • An ordered, mutable collection.

Example:

Key Methods:

Method
Example
Description

append()

fruits.append("grape")

Add an item to the end.

remove()

fruits.remove("banana")

Remove an item.

sort()

fruits.sort()

Sort items.

Tuple

  • An ordered, immutable collection.

Example:

Range

  • Represents a sequence of numbers.

Example:


2.5 Mapping Data Type

Dictionary (dict)

  • Stores key-value pairs.

Example:

Operation
Example
Result

Access Value

user["name"]

"Alice"

Add Key-Value

user["city"] = "Paris"

Adds new key-value.

Delete Key

del user["age"]

Removes "age".


2.6 Set Data Type

Set

  • An unordered, unique collection.

Example:

Key Methods:

Method
Example
Description

add()

numbers.add(5)

Add an element.

remove()

numbers.remove(3)

Remove an element.


2.7 NoneType

Represents a variable with no value.


3. Type Conversion

Convert between data types using built-in functions:

  • int(): Convert to integer.

  • float(): Convert to float.

  • str(): Convert to string.

Example:


4. Tricks and Precautions

  1. Dynamic Typing: Be cautious with changing variable types, as it may lead to bugs.

  2. Immutable vs. Mutable:

    • Immutable: str, tuple.

    • Mutable: list, dict, set.

  3. Copying Data:

    • Use copy() for mutable types to avoid unintended changes.

  4. Avoid Shadowing Built-ins: Don’t use names like list, str, or input as variable names.


Summary Table: Data Types in Python

Category
Type
Examples
Notes

Numeric

int

1, -3, 42

Whole numbers.

float

3.14, -0.01

Numbers with decimals.

complex

3 + 4j

Real + imaginary parts.

Text

str

"hello", 'world'

Immutable sequences of chars.

Sequence

list

[1, 2, 3]

Mutable, ordered collection.

tuple

(1, 2, 3)

Immutable collection.

range

range(5)

Sequence of numbers.

Set

set

{1, 2, 3}

Unordered, unique collection.

Mapping

dict

{"key": "value"}

Key-value pairs.

Boolean

bool

True, False

Logical values.

NoneType

None

None

Represents no value.


Last updated