Basic Data Types in Python

May 17, 2024

Basic Data Types in Python

Lecturer: Siddharthan

This lecture focuses on the basic data types in Python, the second module of a hands-on machine learning course with Python. This is the third video in this module.

Data Types in Python

The five basic data types in Python are:

  1. Integer (int)
  2. Floating Point (float)
  3. Complex (complex)
  4. Boolean (bool)
  5. String (str)

Integer

  • Real numbers without a fractional component.
  • Example: a = 8
  • Check the data type: type(a) -> int
  • Printing: print(a) -> 8

Floating Point

  • Decimal numbers.
  • Example: b = 2.3
  • Check the data type: type(b) -> float
  • Printing: print(b) -> 2.3

Complex

  • Numbers with both real and imaginary parts.
  • Example: c = 1 + 3j (here 1 is real, 3j is imaginary)
  • Check the data type: type(c) -> complex
  • Printing: print(c) -> 1+3j

Conversion Between Data Types

  • Integer to Float:
    x = 10
    y = float(x)
    
    Results:
    • print(y) -> 10.0
    • type(y) -> float
  • Float to Integer:
    x = 5.88
    y = int(x)
    
    Results:
    • print(y) -> 5 (removes decimal, does not round)
    • type(y) -> int

Boolean

  • Represents True or False.
  • Example:
    a = True
    b = False
    
    Check the data type: type(a) -> bool
    • Can be used in conditions. Example:
    a = 7 > 3
    
    • print(a) -> True
    • type(a) -> bool

String

  • Text or statements enclosed in quotes (") or (").
  • Example: my_string = "Machine Learning"
  • Check the data type: type(my_string) -> str
  • Printing: print(my_string) -> Machine Learning
  • *Operations on Strings:
    • Replication:
      print("Hello" * 5)
      
      Results: HelloHelloHelloHelloHello
    • Slicing:
      s = "Programming"
      print(s[0:5])  # Output: 'Progr'
      
    • Step Slicing:
      s = "Programming"
      print(s[0:10:2])  # Output: 'Pormn'
      
    • Concatenation:
      word1 = "Machine"
      word2 = "Learning"
      print(word1 + " " + word2)
      
      Results: Machine Learning

Summary

  • Discussed five basic data types in Python.
  • Example code snippets to define, print, and convert between data types.
  • Basic operations on each data type, especially strings.
  • Next video will cover more advanced data types like lists and tuples.