Python
  • Intro.
  • Catalogue
  • Chapter 1: Introduction to Python
  • Chapter 2: Python Syntax and Fundamentals
    • Chapter: Variables and Data Types in Python
  • Chapter 3: Control Flow
  • Chapter 4: Functions
  • Chapter 5: Data Structures
  • Chapter 6: Object-Oriented Programming (OOP)
  • Chapter 7: Modules and Packages
  • Chapter 8: File Handling
  • Chapter 9: Error and Exception Handling
  • Chapter 10: Working with Databases
  • Chapter 11: Iterators and Generators
  • Chapter 12: Decorators and Context Managers
  • Chapter 13: Concurrency and Parallelism
  • Chapter 14: Testing and Debugging
  • Chapter 15: Web Development with Python
  • Chapter 16: Data Science and Machine Learning with Python
  • Chapter 17: Working with APIs
  • Chapter 18: Automation with Python
  • Chapter 19: Python and Cloud/DevOps
  • Chapter 20: Python and IoT
  • Appendices
Powered by GitBook
On this page
  • 1. Variables in Python
  • 2. Data Types in Python
  • 3. Type Conversion
  • 4. Tricks and Precautions
  • Summary Table: Data Types in Python
  1. Chapter 2: Python Syntax and Fundamentals

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:

x = 5      # Integer
name = "Alice"  # String
is_logged_in = True  # Boolean

Multiple Assignments

You can assign multiple variables in one line:

a, b, c = 1, 2, 3  # a=1, b=2, c=3
x = y = z = 0  # x, y, z all equal 0

Reassigning Variables

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

x = 42
x = "Now I'm a string"

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:

age = 21
negative = -99
large_number = 12345678901234567890

Float (float)

  • Numbers with decimal points or in exponential form.

Example:

pi = 3.14159
e = 2.718e3  # Scientific notation (equals 2718.0)

Complex (complex)

  • Numbers with a real and imaginary part.

Example:

z = 3 + 4j  # 3 is the real part, 4j is the imaginary part
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:

greeting = "Hello, World!"
single_quote = 'Python is fun'
multi_line = """This is
a multiline
string."""

Tricks & Precautions:

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

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

escaped = "He said, \"Python is awesome!\""

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:

is_active = True
has_errors = False

Booleans are often used in conditions:

if is_active:
    print("The user is active.")

2.4 Sequence Data Types

List

  • An ordered, mutable collection.

Example:

fruits = ["apple", "banana", "cherry"]

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:

coordinates = (10, 20)

Range

  • Represents a sequence of numbers.

Example:

nums = range(5)  # 0, 1, 2, 3, 4

2.5 Mapping Data Type

Dictionary (dict)

  • Stores key-value pairs.

Example:

user = {"name": "Alice", "age": 25}
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:

numbers = {1, 2, 3, 4, 4}  # Output: {1, 2, 3, 4}

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.

nothing = None

3. Type Conversion

Convert between data types using built-in functions:

  • int(): Convert to integer.

  • float(): Convert to float.

  • str(): Convert to string.

Example:

x = "123"
y = int(x)  # Converts string to int

4. Tricks and Precautions

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

    x = "5"
    x = x + 2  # Error: Can't add str and int
  2. Immutable vs. Mutable:

    • Immutable: str, tuple.

    • Mutable: list, dict, set.

  3. Copying Data:

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

    original = [1, 2, 3]
    copy = original.copy()
  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.


PreviousChapter 2: Python Syntax and FundamentalsNextChapter 3: Control Flow

Last updated 4 months ago