Session 2

🎨 Data Types in Python

Understanding the different kinds of data Python can handle

πŸ“š 6 Topics ⏱️ 45 min read 🎯 Foundation Level

πŸ—ΊοΈ What You'll Learn

πŸ”’ Numeric Types (int, float, complex)
πŸ“ Text/String Type
βœ… Boolean Type
🚫 NoneType
πŸ”„ Type Conversion
πŸ” type() Function

πŸ“˜ Same topic in the course notebook

Session_2 Data Types notebooks cover int, float, string, bool, type(), and castingβ€”same as this lesson. Open the notebook and run the cells next to this page.

πŸŽ’

Think of It Like a Backpack!

Imagine your backpack can hold different things:

πŸ“š Books = Integers (whole things)
πŸ§ƒ Water bottle = Float (can be partially full: 0.5 liters)
πŸ“ Notes = Strings (written text)
πŸ’‘ Flashlight = Boolean (ON or OFF)
πŸ‘» Empty pocket = None (nothing there!)

Just like you organize different items differently in your backpack, Python needs to know what "type" of data it's working with!

πŸ“Š Python Data Type Overview

🌳 The Data Type Family Tree

                    Python Data Types
                          β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚                 β”‚                 β”‚
    πŸ“Š NUMERIC        πŸ“ TEXT           πŸ”˜ SPECIAL
        β”‚                 β”‚                 β”‚
   β”Œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”         string           β”Œβ”€β”€β”€β”΄β”€β”€β”€β”
   β”‚    β”‚    β”‚                          β”‚       β”‚
  int float complex                   bool    None
   β”‚    β”‚    β”‚                          β”‚       β”‚
  42  3.14  2+3j                    True/False  βˆ…
        
πŸ’‘ Quick Reference

Every piece of data in Python has a type. Use type() to discover it!

πŸ”’ Numeric Data Types

2.1

πŸ“¦ Integers (int) - Whole Numbers

Integers are whole numbers without any decimal point. They can be positive, negative, or zero.

🌍
Real World Examples:
  • Your age: 25 years (not 25.5!)
  • Number of apples: 10 apples
  • Floor number: -2 (basement)
  • Bank balance: -500 (overdrawn πŸ˜…)
Python From Source
# Integer examples from Session 2
a = 5          # Positive integer
b = -3         # Negative integer
c = 0          # Zero is also an integer!
large_num = 1000000  # Large numbers work too

# Check the type
print(type(a))  # Output: <class 'int'>
print(type(b))  # Output: <class 'int'>
Output
<class 'int'>
<class 'int'>
2.2

🌊 Floating Point (float) - Decimal Numbers

Floats are numbers with a decimal point. The name "floating point" comes from how the decimal point can "float" to different positions.

🎯 Why "Floating" Point?

    123.456  β†’  1.23456 Γ— 10Β²
    0.00123  β†’  1.23 Γ— 10⁻³
    
    The decimal "floats" to create 
    a standard form! 🎈
            
🌍
Real World Examples:
  • Temperature: 98.6Β°F
  • Price: $19.99
  • Height: 5.8 feet
  • Pi: 3.14159...
Python From Source
# Float examples from Session 2
pi = 3.14
temperature = 98.6
negative_float = -2.5
scientific = 1.5e10  # Scientific notation: 15,000,000,000

# Check the types
print(type(pi))           # Output: <class 'float'>
print(type(temperature))   # Output: <class 'float'>
print(type(scientific))    # Output: <class 'float'>
Output
<class 'float'>
<class 'float'>
<class 'float'>
⚠️ Float Precision Warning

Floats can sometimes be slightly imprecise due to how computers store decimal numbers:

0.1 + 0.2 = 0.30000000000000004 (not exactly 0.3!)
2.3

πŸŒ€ Complex Numbers

Complex numbers have a real part and an imaginary part. Python uses j for the imaginary unit (mathematicians use i).

🎨 Visualizing Complex Numbers

        Imaginary (j)
              ↑
              β”‚    β€’ (3+4j)
            4 β”‚    β”‚
              β”‚    β”‚
        ──────┼────┴───────→ Real
              β”‚    3
              β”‚
              
    A complex number is like a point 
    on a 2D plane! πŸ“
            
🌍
Where Complex Numbers Are Used:
  • Electrical Engineering (AC circuits)
  • Signal Processing
  • Quantum Physics
  • Control Systems
Python From Source
# Complex number examples from Session 2
z = 3 + 4j
w = complex(2, 5)  # Another way to create: 2+5j

# Access real and imaginary parts
print("Real part:", z.real)      # Output: 3.0
print("Imaginary part:", z.imag)  # Output: 4.0
print(type(z))                    # Output: <class 'complex'>

# Complex arithmetic
sum_complex = z + w
print("Sum:", sum_complex)  # Output: (5+9j)
Output
Real part: 3.0
Imaginary part: 4.0
<class 'complex'>
Sum: (5+9j)

πŸ“ String Data Type (str)

2.4

✍️ Strings - Text Data

Strings are sequences of characters - basically text! They can contain letters, numbers, symbols, spaces, and even emojis.

πŸ“Ώ Think of Strings as Beads on a Necklace

    "Hello"
    
    β”Œβ”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”
    β”‚ H β”‚ e β”‚ l β”‚ l β”‚ o β”‚
    β””β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”˜
      0   1   2   3   4   ← Index numbers
      
    Each character is a "bead" you can access!
            
Python From Source
# String examples from Session 2
name = "Alice"             # Double quotes
greeting = 'Hello World'   # Single quotes work too!
mixed = "I'm learning Python"  # Mix when needed

# Multi-line strings with triple quotes
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""

print(type(name))     # Output: <class 'str'>
print(type(greeting))  # Output: <class 'str'>
print(poem)
Output
<class 'str'>
<class 'str'>
Roses are red,
Violets are blue,
Python is awesome,
And so are you!

πŸ”€ String Operations

Python From Source
# String concatenation (joining)
first = "Hello"
second = "World"
combined = first + " " + second
print(combined)  # Output: Hello World

# String repetition
laugh = "Ha" * 3
print(laugh)  # Output: HaHaHa

# String length
print(len(combined))  # Output: 11

# Accessing characters (indexing)
word = "Python"
print(word[0])   # Output: P (first character)
print(word[-1])  # Output: n (last character)
Output
Hello World
HaHaHa
11
P
n
πŸ’‘ Pro Tip: Numbers in Strings

"42" is a STRING, not a number! You can't do math with it directly:

"42" + "8" = "428" (concatenation, not addition!)

βœ… Boolean Data Type (bool)

2.5

πŸ”˜ Booleans - True or False

Booleans are the simplest data type - they can only be True or False. Named after mathematician George Boole!

πŸ’‘ The Light Switch of Programming

       True              False
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚   ON    β”‚      β”‚   OFF   β”‚
    β”‚   πŸ’‘    β”‚      β”‚   πŸ”Œ    β”‚
    β”‚    1    β”‚      β”‚    0    β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    
    Only 2 states. Nothing in between!
            
🌍
Real World Boolean Questions:
  • Is the user logged in? β†’ True/False
  • Is the age β‰₯ 18? β†’ True/False
  • Did the payment succeed? β†’ True/False
  • Is the file empty? β†’ True/False
Python From Source
# Boolean examples from Session 2
is_sunny = True
is_raining = False

print(type(is_sunny))  # Output: <class 'bool'>

# Booleans from comparisons
x = 10
y = 5

print(x > y)    # Output: True
print(x < y)    # Output: False
print(x == y)   # Output: False
print(x != y)   # Output: True

# Boolean logic
print(is_sunny and is_raining)  # Output: False (both must be True)
print(is_sunny or is_raining)   # Output: True (at least one is True)
print(not is_raining)           # Output: True (flips False to True)
Output
<class 'bool'>
True
False
False
True
False
True
True

🎯 Boolean Logic Truth Table

A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True

🚫 NoneType

2.6

πŸ‘» None - The Absence of Value

None represents the absence of a value. It's not zero, not empty string, not False - it's literally "nothing".

🎁 Understanding None

    πŸ“¦ Empty Box = ""     (empty string - box exists!)
    πŸ“¦ Box with 0 = 0     (zero - a number in the box!)
    πŸ“­ No Box = None      (no box at all!)
    
    None means the value doesn't exist yet,
    or was deliberately set to "nothing"
            
🌍
When You Might See None:
  • A function that doesn't return anything
  • A variable before you assign a value
  • When data is missing from a database
  • Default value for optional parameters
Python From Source
# None examples from Session 2
nothing = None

print(nothing)           # Output: None
print(type(nothing))     # Output: <class 'NoneType'>

# Checking for None
if nothing is None:
    print("The variable has no value!")

# Functions that return None
def say_hello(name):
    print(f"Hello, {name}!")
    # No return statement = returns None

result = say_hello("Alice")
print("Function returned:", result)  # Output: None
Output
None
<class 'NoneType'>
The variable has no value!
Hello, Alice!
Function returned: None
⚠️ Important: Check for None with 'is', not '=='

Always use if x is None instead of if x == None. It's the Pythonic way and more reliable!

πŸ”„ Type Conversion (Casting)

2.7

🎭 Changing Data Types

Sometimes you need to convert data from one type to another. This is called type casting or type conversion.

πŸ¦‹ Type Conversion = Transformation

    "42"  ──→  int("42")  ──→  42
    🧡 String    πŸ”„ Cast     πŸ”’ Integer
    
    42  ──→  str(42)  ──→  "42"
    πŸ”’ Int   πŸ”„ Cast   🧡 String
    
    Like converting currencies! πŸ’±
            
Python From Source
# Type conversion examples from Session 2

# String to Integer
age_string = "25"
age_int = int(age_string)
print("Type:", type(age_int), "Value:", age_int)

# String to Float
price_string = "19.99"
price_float = float(price_string)
print("Type:", type(price_float), "Value:", price_float)

# Number to String
num = 100
num_string = str(num)
print("Type:", type(num_string), "Value:", num_string)

# Float to Integer (truncates decimal!)
pi = 3.99
pi_int = int(pi)
print("Float to Int:", pi_int)  # Output: 3 (not rounded!)

# Integer to Float
whole = 5
decimal = float(whole)
print("Int to Float:", decimal)  # Output: 5.0
Output
Type: <class 'int'> Value: 25
Type: <class 'float'> Value: 19.99
Type: <class 'str'> Value: 100
Float to Int: 3
Int to Float: 5.0

πŸ”’ Boolean Conversion

Python From Source
# Boolean conversions from Session 2

# Numbers to Boolean
print(bool(0))      # False (zero is falsy)
print(bool(1))      # True (any non-zero is truthy)
print(bool(-5))     # True
print(bool(0.0))    # False

# Strings to Boolean
print(bool(""))       # False (empty string is falsy)
print(bool("Hello")) # True (any non-empty string is truthy)
print(bool("False")) # True (it's a non-empty string!)

# None to Boolean
print(bool(None))   # False
Output
False
True
True
False
False
True
True
False
πŸ’‘ Truthy vs Falsy

Falsy values: 0, 0.0, "", None, False, [], {}

Everything else is Truthy!

πŸ” The type() Function

2.8

πŸ•΅οΈ Detecting Data Types

The type() function is your detective tool - it tells you exactly what type of data you're working with!

Python From Source
# type() examples from Session 2

# Check types of various values
print(type(42))        # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type("hello"))   # <class 'str'>
print(type(True))      # <class 'bool'>
print(type(None))      # <class 'NoneType'>
print(type(2+3j))      # <class 'complex'>

# Useful for debugging!
mystery_value = "100"
if type(mystery_value) == str:
    print("It's a string! Converting to int...")
    mystery_value = int(mystery_value)
print("Final value:", mystery_value, "Type:", type(mystery_value))
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
<class 'complex'>
It's a string! Converting to int...
Final value: 100 Type: <class 'int'>

πŸ“‹ Quick Reference Card

Type Example Check Convert
int 42, -10, 0 type(x) == int int("42")
float 3.14, -2.5 type(x) == float float("3.14")
str "hello", '42' type(x) == str str(42)
bool True, False type(x) == bool bool(1)
complex 2+3j type(x) == complex complex(2, 3)
NoneType None x is None N/A

🎯 Practice Exercises

Exercise 1 Easy

Create variables of each data type and print their types.

πŸ’‘ Show Solution
my_int = 25
my_float = 3.14
my_str = "Hello"
my_bool = True
my_none = None

print(type(my_int))    # <class 'int'>
print(type(my_float))  # <class 'float'>
print(type(my_str))    # <class 'str'>
print(type(my_bool))   # <class 'bool'>
print(type(my_none))   # <class 'NoneType'>
Exercise 2 Medium

Convert the string "3.14159" to a float, then to an integer. What happens to the decimal?

πŸ’‘ Show Solution
pi_string = "3.14159"
pi_float = float(pi_string)
pi_int = int(pi_float)

print(pi_float)  # 3.14159
print(pi_int)    # 3 (decimal part is truncated!)

🚫 Common Mistakes (Data Types)

πŸ’­ Short reflection

In one sentence: why does Python need different types (int, float, str, bool) instead of treating everything as text?

βœ… CORE (Must know)

πŸ“š NON-CORE (Good to know)

Complete code from course notebook: 2_Data_Types (1) (1).ipynb

Every line of code from the course notebook (verbatim).

# --- Code cell 2 ---
5 types
1@ numerical---int,float,complex
2@ sequential---string,list,tuple
3@ set-set
4@ map-dict
5@ bollean
6@ Nonetype

# --- Code cell 3 ---
string_ = 'Python 3'
print(string_)
print (type(string_))

# --- Code cell 6 ---
age = 30
print('Age:',age)
print (type(age))

# --- Code cell 8 ---
Height = -153.5
type(Height)

# --- Code cell 9 ---
# complex---real+imag
#a+bj---i(sqrt(-1)

# --- Code cell 10 ---
d=5+6j
type(d)

# --- Code cell 12 ---
345>230

# --- Code cell 13 ---
345>2300

# --- Code cell 15 ---
# this is my 2nd session

# --- Code cell 16 ---
#doc_string/multi line comment=
""" this
    is
    a
    multi line comment"""

# --- Code cell 17 ---
name='12344'

# --- Code cell 18 ---
type(name)

# --- Code cell 21 ---
"Data".upper()

# --- Code cell 23 ---
"DATA".lower()

# --- Code cell 25 ---
"data science is a emerging field".title()

# --- Code cell 27 ---
"data science".capitalize()

# --- Code cell 29 ---
"DaTA".swapcase()

# --- Code cell 31 ---
"  data science   ".strip()

# --- Code cell 33 ---
"  data science".lstrip()

# --- Code cell 35 ---
"data science   ".rstrip()

# --- Code cell 37 ---
text = " I am learning's Python! "
print(text.replace("learn", "teach"))

# --- Code cell 39 ---
text = "I like cricket, I play cricket, India will,win 2023 world cup."
print(text.split(","))

# --- Code cell 40 ---
#splitting string based on seperator
text = "I like cricket! I play! cricket; India! will win! 2023 world cup."
print(text.split("!"))

# --- Code cell 41 ---
user="FanTAstic ShoW It IS"
print(user.swapcase())

# --- Code cell 43 ---
text = "cricket"
text.isalpha()

# --- Code cell 44 ---
text = "cricket_2"
text.isalpha()

# --- Code cell 46 ---
text = "1123456q"
text.isdigit()

# --- Code cell 47 ---
text = "T20"
text.isdigit()

# --- Code cell 49 ---
text = "T2034qq@"
text.isalnum()

# --- Code cell 51 ---
text = "I like cricket, I play cricket, India wIll win 2023 world cup."
text.count('c')

# --- Code cell 52 ---
text = "Predicting Fruit Type from Size & Color"

# Remove spaces, then count characters
char_count = len(text.replace(" ", ""))

print(f"Total characters (no spaces): {char_count}")

# --- Code cell 53 ---
customer = "John Doe"
item = "Laptop"
price = 799.99678567

# Format and display receipt
receipt = print(f"Customer: {customer}\nItem: {item}\nPrice: ${price:.2f}")

# --- Code cell 54 ---
full_name = "Alice Johnson"
username = full_name.lower().replace(" ", "_")
print(username)

# --- Code cell 56 ---
start_year = 2023
text = "Inttrvu.ai was launched in {}"
print(text.format(start_year))

# --- Code cell 57 ---
#Number in {} indicates index of parameter passed to format
start_year = 2023
start_month = 7
text = "Inttrvu.ai was launched in {1}th month of year {0}"
print(text.format(start_year, start_month))

# --- Code cell 60 ---
text = "T20"
len(text)

# --- Code cell 61 ---
text = "I like cricket, I play cricket, India will win 2023 world cup."
len(text)

# --- Code cell 62 ---
# indexing---retreiving a single element of a data
text = "I like cricket, I play cricket, India will win 2023 world cup."

# --- Code cell 63 ---
list1=[2,3,4,5,6,77,7,8]
#       0 1 2 3 4 5.......+ve
#            .... -2  -1  -ve

# --- Code cell 64 ---
list1[-1]

# --- Code cell 65 ---
len(list1)

# --- Code cell 66 ---
#list1[-3:-6:-1]
#list1[3:6:-1]
list1[-3:-6:1]

# --- Code cell 67 ---
list1[::-1]

# --- Code cell 68 ---
list1[-3]

# --- Code cell 69 ---
text[5]

# --- Code cell 71 ---
"Python"[0:3]

# --- Code cell 72 ---
"Python"[3:]

# --- Code cell 74 ---
"Python"[-1]

# --- Code cell 75 ---
"Python"[-3:]

# --- Code cell 77 ---
"Python"[1::2] #Starts at index 1, skips every 2nd character

# --- Code cell 78 ---
"DataScience"[1:10:2] #Starts at index 1, Stops at index 10 (exclusive),skips every 2nd character

# --- Code cell 81 ---
a , b , c = "Red", "Blue", "Green"
print(a)
print(b)
print(c)

# --- Code cell 82 ---
a = b = c = "Red"
print(a)
print(b)
print(c)

# --- Code cell 83 ---
a , b , c = "Red", "Blue", "Green"
print(a, b, c)

# --- Code cell 84 ---
a  = "data"
b  = "frame"
print(a + b)
print(a +" "+ b)
print(a +' '+ b)

Complete code from course notebook: Data_Types_part1 (1) (1).ipynb

Every line of code from the course notebook (verbatim).

# --- Code cell 1 ---
# data types----define the kind of data a variable can hold

# --- Code cell 2 ---
# in other languages like c,c++ and java you must declare the type of varaiable but in python
# python will automatically understand whether the given value is an int,float or list...

# --- Code cell 3 ---
c="hello"

# --- Code cell 4 ---
type(c)

# --- Code cell 5 ---
# 6 types
1@ Numerical data types---INT,FLOAT and complex
2@ Sequential data types---string,list and tuple
3@ set data type--set
4@ mapping data type---Dictionary
5@ Boolean data type---Boolean
6@ None type

# --- Code cell 6 ---
Numerical data type

# --- Code cell 7 ---
# integer--INT
# represents whole numbers where it can handle +ve,-Ve and zero

# --- Code cell 8 ---
weight=56

# --- Code cell 9 ---
weight

# --- Code cell 10 ---
# check the data type----built-in-function--type()

# --- Code cell 11 ---
print("weight:",weight)
print(type(weight))

# --- Code cell 12 ---
# print()---built-in-function---used to display the output

# --- Code cell 13 ---
type(weight)

# --- Code cell 14 ---
height=-345
type(height)

# --- Code cell 15 ---
age=45
score=99
print(age)
print(score)

# --- Code cell 16 ---
# float---represents real numbers with decimal points

# --- Code cell 17 ---
height=-179.99

# --- Code cell 18 ---
type(height)

# --- Code cell 19 ---
yellow=-333.33
print(type(yellow))

# --- Code cell 20 ---
zer=0

# --- Code cell 21 ---
type(zer)

# --- Code cell 22 ---
a+ib

# --- Code cell 23 ---
# complex---represents real and imaginary part
# complex_number=real_part+imiginary_part*j
# a+bj

# --- Code cell 24 ---
# j is used to denote the imaginary unit(as in maths i ,but in python it is j) sqrt(-1)

# --- Code cell 26 ---
c=4+7j  #---literal notation
type(c)

# --- Code cell 27 ---
# complex constructor
c2=complex(4,5)
print(c2)

# --- Code cell 28 ---
int()
float()
complex()

# --- Code cell 29 ---
real=int(input("enter a real part: "))

# --- Code cell 30 ---
# complex number defining by user
real=int(input("enter a real part: "))
imag=float(input("enter a imag part: "))
c3=complex(real,imag)
print("complex_number:",c3)

# --- Code cell 31 ---
x=None
print(type(x))

# --- Code cell 32 ---
# high level language---memory accesing and intergrated data type

# --- Code cell 33 ---
# Type casting---means converting one data type into another
# example---converting int to float ,float to complex

# --- Code cell 34 ---
1@ implicit type casting
2@ Explicit type casting

# --- Code cell 36 ---
basic_salary=6500
bonus=349.87
result=basic_salary+bonus

# --- Code cell 37 ---
result

# --- Code cell 38 ---
print(type(result))

# --- Code cell 39 ---
maths=56
science=34
score=maths/science

# --- Code cell 40 ---

print(score)
print(type(score))

# --- Code cell 42 ---
salary=4566.656
type(salary)

# --- Code cell 43 ---
salary=int(salary)
salary

# --- Code cell 44 ---
type(salary)

# --- Code cell 45 ---
salary=float(salary)
salary

# --- Code cell 46 ---
type(salary)

# --- Code cell 47 ---
y=complex(salary)

# --- Code cell 48 ---
type(y)

# --- Code cell 49 ---
y

# --- Code cell 50 ---
z=float(y)

# --- Code cell 51 ---
f=int(y)

# --- Code cell 52 ---
---any type of int and float can convert into any type
---but complex data type cannot convert into int and float

# --- Code cell 53 ---
tee=678.899
d=complex(tee)
d

# --- Code cell 54 ---
f=float(d)
f

# --- Code cell 55 ---
s=6765
y=6+7j
g=s+y
g