Exploring Python Data Types

Sep 25, 2024

Python Data Types Lecture Notes

Introduction

  • Overview of numeric and string data types in Python.
  • Explanation of identifiers in Python (e.g., function names, module names).

Data Types in Python

  • Definition: A data type in Python defines the type of value a variable can hold.
  • Python is dynamically typed — variable types are determined at runtime.

Numeric Data Types

  1. Integer

    • Represents whole numbers (positive or negative) without decimals.
    • Used in arithmetic operations like addition, subtraction, multiplication.
    • Example: x = 10, y = 5
  2. Float

    • Represents real numbers, includes a decimal point.
    • Example: a = 3.14, b = -75
    • Can use scientific notation (e.g., x = 3e-10 for 3x10^(-10)).
  3. Complex

    • Has real and imaginary parts, with imaginary part denoted by j.
    • Example: c = 2 + 3j, d = -1 + 4j

Checking Data Types

  • Use the type() function to check variable types.
  • Examples:
    • number_one = 15 returns <class 'int'>
    • number_two = -3.57 returns <class 'float'>
    • number_three = 3 + 4j returns <class 'complex'>

String Data Type

  • Strings are sequences of characters enclosed in quotes.
  • Single-line strings can use single or double quotes.
  • Multi-line strings use triple quotes.
  • Example: name_1 = "Par Roy" or name_2 = 'Par Roy'

String Operations

  • Concatenation: Use + to join strings, e.g., name_3 = name_1 + name_2.
  • Repetition: Use * to repeat strings, e.g., name_3 * 2.
  • Indexing: Use square brackets to access characters, starting from index 0.
    • Example: name_3[0] returns P, name_3[1] returns second character.

Boolean Data Type

  • Boolean variables store True or False.
  • Operations include comparison and equality checking.
    • Example: x > y, x == 5

Type Conversion

  • Implicit Conversion: Automatic conversion performed by Python.
    • Example: converting int to float during operations.
  • Explicit Conversion: Manual conversion using functions like int(), float(), etc.
    • Example: number_3 = int(number_2) converts float to int.

Conclusion

  • Reviewed types such as implicit and explicit type conversions.
  • End of session, with a reminder to see future classes.