foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand Python's core data types
  • Differentiate between integers, floats, strings, and booleans
  • Learn when to use each data type
  • Check and identify variable types

Data Types in Python

Imagine you're organizing your closet. You wouldn't put shoes in your sock drawer or hang socks on hangers, right? Everything has its proper place and category. Data types in programming work the same way – they help Python understand what kind of information you're working with and how to handle it.

When you tell Python that something is a number, it knows it can do math with it. When you say it's text, it knows it can search through it or combine it with other text. Understanding data types is like learning the language that helps you communicate clearly with your computer.


The Four Foundational Data Types

Python has several data types, but let's start with the four you'll use most often:


              Python's Core Data Types                            

                                                                  
   INTEGERS (int)               FLOATS (float)                  
   Whole numbers                Decimal numbers                 
   42, -17, 0, 1000000          3.14, -0.5, 2.0                 
                                                                  
   STRINGS (str)                BOOLEANS (bool)                 
   Text in quotes               True or False                   
   "Hello", 'Python'            True, False                     
                                                                  

If we take the example of a restaurant menu:

  • Integers are like counting items: "3 pizzas, 2 drinks"
  • Floats are like prices: "$19.99, $5.50"
  • Strings are like item names: "Margherita Pizza", "Coca-Cola"
  • Booleans are like availability: Available (True) or Sold Out (False)

Integers (int) – Whole Numbers

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

Real-World Analogies

Integer Example Real-World Context
age = 25 Your age in years
students = 30 Number of students in a class
temperature = -5 Temperature in winter
floor = 0 Ground floor in a building
score = 1000000 Points in a game

Working with Integers

# Counting things
apples = 5
oranges = 3
total_fruits = apples + oranges  # 8

# Age and years
birth_year = 1995
current_year = 2024
age = current_year - birth_year  # 29

# Large numbers - Python handles them easily!
world_population = 8000000000
distance_to_moon = 384400  # kilometers

Python handles large integers easily - there's no size limit. You can work with numbers as large as your computer's memory allows.

When to Use Integers


                 Use Integers When...                             

                                                                  
  Counting items (people, products, clicks)                   
  Ages, years, days                                           
  Indexes and positions                                       
  Scores and points                                           
  Quantities that can't be fractional                         
                                                                  

Floats (float) – Decimal Numbers

Floats (floating-point numbers) represent numbers with decimal points. They're essential for precision.

Real-World Analogies

Float Example Real-World Context
price = 19.99 Price of an item
temperature = 36.6 Body temperature
pi = 3.14159 Mathematical constant
percentage = 0.85 85% as a decimal
gpa = 3.75 Grade point average

Working with Floats

# Prices and money
product_price = 29.99
tax_rate = 0.08
total = product_price * (1 + tax_rate)  # 32.39 (approximately)

# Measurements
height_meters = 1.75
weight_kg = 70.5

# Scientific values
pi = 3.14159
speed_of_light = 299792458.0  # meters per second

The Float Precision Reality

Here's something important: computers store floats in binary, which can lead to tiny precision issues:

result = 0.1 + 0.2
print(result)  # 0.30000000000000004 (not exactly 0.3!)

This is normal! For most purposes, it doesn't matter. For financial calculations, Python has a special Decimal module.

Integer vs Float Division

# Division always returns a float
result = 10 / 4      # 2.5 (float)

# Integer division (floor division)
result = 10 // 4     # 2 (int)

# This catches many beginners!
print(type(10 / 2))  # <class 'float'> → 5.0, not 5!

Strings (str) – Text Data

Strings are sequences of characters – essentially text. They're enclosed in quotes.

The Quote Options

# Single quotes
name = 'Alice'

# Double quotes (same as single)
greeting = "Hello, World!"

# Triple quotes for multi-line
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""

# When to use which?
message = "It's a beautiful day"     # Use " when text has '
message = 'He said "Hello"'          # Use ' when text has "
message = """It's "awesome"!"""      # Use """ when text has both

Real-World String Examples

String Example Real-World Context
name = "Alice" User's name
email = "user@mail.com" Email address
password = "secret123" Password
message = "Welcome back!" Notification
address = "123 Main St" Street address

Strings Are Not Numbers!

This is a critical concept:

# These look similar but are VERY different!
number = 42        # Integer – can do math
text = "42"        # String – it's text that looks like a number

print(number + 8)  # 50 (math works)
print(text + "8")  # "428" (concatenation, not math!)

# This will cause an error:
# print(text + 8)  # TypeError! Can't add string and int

The Empty String

# An empty string is still a string
empty = ""
print(type(empty))  # <class 'str'>
print(len(empty))   # 0 (zero characters)

Booleans (bool) – True or False

Booleans are the simplest type – they can only be True or False. Named after mathematician George Boole, they're the foundation of all computer logic.

Real-World Analogies

Think of booleans like light switches or yes/no questions:

Boolean Example Real-World Context
is_logged_in = True User session status
has_permission = False Access control
is_adult = True Age verification
email_verified = False Account verification
in_stock = True Product availability

Booleans in Action

# User status
is_premium_member = True
account_active = True
email_verified = False

# Game state
game_over = False
player_alive = True
level_complete = False

# Making decisions
age = 25
is_adult = age >= 18  # True (because 25 >= 18)

temperature = 35
is_hot = temperature > 30  # True

Important: Capitalization Matters!

# Correct - capital T and F
active = True
deleted = False

# Wrong - these are not booleans!
# active = true   # NameError: name 'true' is not defined
# active = TRUE   # NameError: name 'TRUE' is not defined

Booleans Are Numbers Too!

A fascinating Python fact: True equals 1 and False equals 0:

print(True + True)   # 2
print(True * 10)     # 10
print(False + 5)     # 5

# Useful for counting!
votes = [True, True, False, True, False]
yes_count = sum(votes)  # 3

Checking Types with type()

The type() function reveals what type a value is:

# Check various types
print(type(42))         # <class 'int'>
print(type(3.14))       # <class 'float'>
print(type("Hello"))    # <class 'str'>
print(type(True))       # <class 'bool'>

# Store in variables and check
age = 25
price = 19.99
name = "Alice"
active = True

print(type(age))        # <class 'int'>
print(type(price))      # <class 'float'>
print(type(name))       # <class 'str'>
print(type(active))     # <class 'bool'>

Using isinstance() for Type Checking

age = 25

# Check if variable is a specific type
print(isinstance(age, int))     # True
print(isinstance(age, float))   # False
print(isinstance(age, str))     # False

Quick Reference Table

Type Example Use For
int 42, -7, 0 Counting, ages, whole quantities
float 3.14, 19.99 Prices, measurements, calculations
str "Hello", 'World' Text, names, messages
bool True, False Conditions, flags, states

Practical Example: User Profile

Let's see all data types working together:

# A complete user profile using all four types
username = "alice_wonder"        # str: text identifier
age = 28                         # int: whole number
account_balance = 1250.75        # float: decimal amount
is_verified = True               # bool: yes/no status

# Display the profile
print("=" * 35)
print("USER PROFILE")
print("=" * 35)
print(f"Username: {username}")
print(f"Age: {age} years")
print(f"Balance: ${account_balance}")
print(f"Verified: {'Yes' if is_verified else 'No'}")
print("=" * 35)

# Show the types
print("\nData Types Used:")
print(f"username → {type(username).__name__}")
print(f"age → {type(age).__name__}")
print(f"balance → {type(account_balance).__name__}")
print(f"verified → {type(is_verified).__name__}")

Key Takeaways


                   Remember These Points                          

                                                                  
   int: Whole numbers (42, -7, 0)                              
     → Use for counting, ages, quantities                        
                                                                  
  float: Decimal numbers (3.14, 19.99)                        
     → Use for prices, measurements, precise values              
                                                                  
  str: Text in quotes ("Hello", 'World')                      
     → Use for names, messages, any text                         
                                                                  
  bool: True or False (capital letters!)                      
     → Use for conditions, status flags                          
                                                                  
   type(): Check what type something is                        
                                                                  
   "42" is a string, not a number!                             
                                                                  

What's Next?

Now that you understand data types, it's time to learn how to work with them! In the next lesson, we'll explore operators – the tools that let you perform calculations, combine text, and compare values.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service