Python course · Module 1: Python Basics

Data Types - Classifying Discoveries

8 min read ·
In this lesson8

Welcome back to camp! Yesterday "12" + 5 gave me an error instead of 17: "12" is text, 5 is a number. Every good explorer classifies discoveries, and Python's "species" are called data types.

Basic Data Types in Python

In the jungle we meet different life forms - animals, plants, insects. Similarly, Python has different data types.

1. int (Integer) - Whole Numbers

Integers describe everything we count one by one: team members, marching days, specimens. They can be negative and very large:

# Whole numbers - like the number of discovered species
species_count = 42
expedition_day = 7
team_members = 5

# Can be negative
temperature_drop = -5
depth_below_sea = -100

# Python 3 supports very large numbers!
huge_number = 999999999999999999999

Python sizes big numbers itself, so huge_number won't overflow. An int never has a dot.

2. float (Float) - Floating-Point Numbers

Measurements rarely come out even: temperature or distance have decimals. For them we use a float, written with a dot or in scientific notation:

# Numbers with a decimal part
temperature = 32.5
humidity = 78.3
distance_km = 15.7

# Scientific notation
speed_of_light = 3e8  # 3 * 10^8 = 300000000.0 (float!)
tiny_number = 1.5e-10  # 0.00000000015

3e8 always gives a float, even when the result is round. Floats can be imprecise in the last digits: 0.1 + 0.2 is 0.30000000000000004.

3. str (String) - Text

Names, descriptions and notes are text. A string goes in single or double quotes, and a longer description in triple quotes:

# Text in single or double quotes
explorer_name = "Darwin"
location = 'Serengeti'

# Multi-line strings (triple quotes)
description = """
This is a longer description
spanning multiple lines
of text.
"""

# Escape characters
message = "Darwin said: \"Let's explore!\""
path = "C:\\Users\\Darwin\\jungle"  # Windows path

# Raw string (ignores escapes)
path_raw = r"C:\Users\Darwin\jungle"

A backslash changes the next character's meaning: \" puts a quote inside the string, a pair of backslashes gives one. The r prefix turns this off, handy for Windows paths.

4. bool (Boolean) - Logical Values

Is the area safe? Did we find water? A bool answers such questions with just two values:

# Only two values: True or False
is_dangerous = True
found_water = False
is_raining = True

# The result of a comparison is a bool
temperature = 35
is_hot = temperature > 30  # True

age = 15
is_adult = age >= 18  # False

Comparisons always return a bool, so 5 > 3 gives True. Letter case matters: a lowercase true is an unknown name to Python.

Checking Data Types - type()

When you don't know which species you are dealing with, ask Python. The type() function returns the type of a value:

# The type() function shows the variable's type
species_count = 42
print(type(species_count))  # <class 'int'>

temperature = 32.5
print(type(temperature))  # <class 'float'>

name = "Darwin"
print(type(name))  # <class 'str'>

is_safe = True
print(type(is_safe))  # <class 'bool'>

# Practical use
data = 42
if type(data) == int:
    print("This is a whole number!")

<class 'int'> means "the value belongs to the int class". In conditions I recommend isinstance(data, int), which also accepts related types.

Converting Between Types (Type Casting)

Sometimes we need to change the data type - like translating between languages.

String → Int/Float

Most often a number arrives as text, for example from input(). The int() and float() functions translate it into a number:

# String → Int
age_text = "25"
age = int(age_text)
print(age + 5)  # 30

# String → Float
temperature_text = "32.5"
temperature = float(temperature_text)
print(temperature + 2.5)  # 35.0

# WARNING! Error if the string is not a number
# bad_conversion = int("abc")  # ValueError!
# int("42.5")  # also ValueError - int() does not accept a dot

print(int(float("42.5")))  # 42

int() only accepts a whole-number text, so pass text with a dot through float() first, as in the last line.

Int/Float → String

str() works in the other direction. It helps when we join a number with text using +, which does not mix types:

# Int → String
species_count = 42
count_text = str(species_count)
print("Discovered " + count_text + " species")  # String concatenation

# Float → String
temperature = 32.5
temp_text = str(temperature)
message = f"Temperature: {temp_text}°C"

Without str(), the line with + would end with a TypeError. In an f-string the conversion happens by itself.

Int ↔ Float

We can move between numbers in both directions, but going from float to int cuts off the decimal part:

# Int → Float
whole_number = 10
decimal_number = float(whole_number)  # 10.0

# Float → Int (truncates the decimal part!)
decimal = 15.7
whole = int(decimal)  # 15 (NOT 16!)

decimal2 = 15.2
whole2 = int(decimal2)  # 15

int() does not round, it cuts off everything after the dot. For rounding use round(15.7), which gives 16.

Bool Conversions

You can ask any value whether it is "truthy". Zero and empty text are False, while any other number and any non-empty text are True:

# Numbers → Bool
# 0 = False, all others = True
print(bool(0))    # False
print(bool(1))    # True
print(bool(-5))   # True
print(bool(100))  # True

# String → Bool
# Empty string = False, non-empty = True
print(bool(""))       # False
print(bool("Darwin")) # True
print(bool(" "))      # True (a space is a character!)

# Bool → Int
print(int(True))   # 1
print(int(False))  # 0

True is 1 and False is 0, because bool is a kind of int. Hence the hierarchy bool → int → float: an operation on an int and a float gives a float.

Type-Specific Operations

Operations on Numbers (int, float)

Numbers support seven basic operations. Notice the two kinds of division and exponentiation with a double asterisk:

# Basic operations
a = 10
b = 3

print(a + b)   # 13 (addition)
print(a - b)   # 7  (subtraction)
print(a * b)   # 30 (multiplication)
print(a / b)   # 3.333... (division - ALWAYS float!)
print(a // b)  # 3 (floor division)
print(a % b)   # 1 (remainder - modulo)
print(a ** b)  # 1000 (exponentiation: 10^3)

# Operations on floats
x = 5.5
y = 2.5
print(x + y)   # 8.0
print(x * y)   # 13.75

# Mixing int and float → result is float
mixed = 10 + 5.5  # 15.5 (float)

Even 10 / 2 gives 5.0. The // operator drops the remainder, and % returns exactly that remainder, hence 3 and 1.

Operations on Strings

Text has its own tools: joining, repeating, length, uppercase, indexes and slicing:

# Concatenation (joining)
first_name = "Charles"
last_name = "Darwin"
full_name = first_name + " " + last_name
print(full_name)  # Charles Darwin

# Repetition
jungle_cry = "Help! " * 3
print(jungle_cry)  # Help! Help! Help!

# String length
name = "Darwin"
print(len(name))  # 6

# Indexing (from 0!)
text = "Python"
print(text[0])   # P
print(text[1])   # y
print(text[-1])  # n (last character)
print(text.upper())  # PYTHON

# Slicing
word = "Expedition"
print(word[0:4])   # Expe
print(word[4:])    # dition
print(word[:4])    # Expe
print(word[::2])   # Epdto (every other character)

Indexes start at zero, negative ones count from the end. In the slice [0:4] the first number is included, the second is not. upper() returns a new string, text stays unchanged.

None - Special Type

None is a special value meaning "no value", like an empty trap. You will study functions with def in a few lessons:

# None - like an empty box
treasure = None
print(treasure)  # None
print(type(treasure))  # <class 'NoneType'>

# Practical use
def find_species(name):
    if name == "Python regius":
        return "Found!"
    return None  # Not found

result = find_species("Unknown")
if result is None:
    print("Unknown species")

We check for a missing result with is None. None is neither zero nor empty text, it is a separate type.

Practical Example - Expedition Calculator

Let's combine conversions and operations: the program asks for three values, converts their types and computes the average speed:

print("=== Expedition Calculator ===\n")

# Collecting data
distance_text = input("Distance (km): ")
time_text = input("Time (hours): ")
team_size_text = input("Team size: ")

# Converting to the appropriate types
distance = float(distance_text)
time = float(time_text)
team_size = int(team_size_text)

# Calculations
avg_speed = distance / time
distance_per_person = distance / team_size

# Displaying results
print("\n--- RESULTS ---")
print(f"Average speed: {avg_speed:.2f} km/h")
print(f"Distance per person: {distance_per_person:.2f} km")
print(f"Type of distance: {type(distance)}")
print(f"Type of team_size: {type(team_size)}")

{avg_speed:.2f} shows two decimal places instead of 4.666666666666667. It only changes the printout, not the number itself.

Practical Exercise

Create a program that:

  1. Asks for the temperature in Fahrenheit
  2. Converts it to Celsius: C = (F - 32) × 5/9
  3. Displays the result
  4. Says whether it's hot (>30°C), normal (15-30°C), or cold (<15°C)
Code for this lesson: main.py
# Fahrenheit to Celsius conversion calculator

# TODO: Get the temperature in Fahrenheit
fahrenheit = float(input("Temperature in Fahrenheit: "))

# TODO: Calculate Celsius: C = (F - 32) x 5/9
celsius = (fahrenheit - 32) * 5 / 9

# TODO: Display the result
print(f"{fahrenheit}°F = {celsius:.1f}°C")

# TODO: Check if it's hot (>30), normal (15-30), or cold (<15)
if celsius > 30:
    print("Hot in the jungle!")
elif celsius >= 15:
    print("Pleasant temperature")
else:
    print("Cold for a jungle!")

Summary

Before moving on, make sure that:

  • You know the int, float, str, bool and None types
  • You check types with type() and convert them
  • You know the difference between / and //
  • You understand string indexing

In the next lesson Darwin will show you operators - the explorer's mathematical and logical tools!

Remember: a type is the species of your data - check the species before you do anything with it.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which of the following is of type int?

  2. 2. What is the result of: 10 // 3?

  3. 3. What does the % operator return?

  4. 4. What type does the expression 5 > 3 return?

  5. 5. What will 'Python'[0] return?

  6. 6. Which variable name violates Python rules?

  7. 7. What is the type of the result: 10 / 2?

  8. 8. What type is the result of the expression True + 2.5?

  9. 9. What happens when you run int('42.5')?

  10. 10. Which f-string syntax is correct?

  11. 11. What does the 'sep' parameter do in print()?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the numeric types by the hierarchy from the lesson, from the narrowest to the widest (an operation's result takes the wider type):

  • Horizontal ordering

    Order the steps of conversion string → int → float:

  • Horizontal ordering

    Order operations by result (from smallest):

  • Vertical ordering

    Order the steps of a program that gets the user's age:

  • Vertical ordering

    Order the steps of a program converting Fahrenheit → Celsius:

  • Vertical ordering

    Order the code that checks a variable's type:

  • Code editor

    Create a variable temperature with the value 32.5 and print its type with print() and type():

  • Code editor

    Convert the text '42' to an integer with int() and store the result in the variable number:

  • Horizontal ordering

    Arrange an f-string that gives the text Hello Darwin for name = 'Darwin':

  • Code editor

    Divide 10 by 3 in two ways: store the result of / in normal_division and the result of // in integer_division, then print both:

  • Code editor

    Cut the first 4 characters from the word 'Python' (slice [:4]), store them in the variable first_four and print them:

  • Click in order

    Build a call that checks the type of the variable name:

  • Vertical ordering

    Order the steps of a BMI calculator:

  • Click in order

    Build a call that converts the text "3.14" to a floating-point number:

  • Click in order

    Click in the correct order to create a variable: name = 'Darwin'

  • Click in order

    Click in order: print(f'Hello {name}!')

  • Code editor

    Print the Safari Base Camp menu: a title and 4 numbered options (1. to 4.), each on its own print() line:

  • Code editor

    Print the menu, read the choice with input() into the variable choice, convert it to a number: choice_number = int(choice) and print the chosen option:

  • Horizontal ordering

    Arrange the elements in the correct order:

  • Code editor

    Read the distance (km) and the walking time (h) with float(input()), calculate avg_speed = distance / time and print the result:

  • Code editor

    Read the explorer's name, the location and the number of species with input() (species_found = int(input(...))) and print the daily report with f-strings:

  • Click in order

    Click the elements in the correct order:

  • Code editor

    Combine the parts into one program: print the menu with options 1-4, read the choice, then the distance (km) and the time (h), calculate avg_speed = distance / time and print a report with the result:

  • Horizontal ordering

    Arrange the elements in the correct order:

  • Vertical ordering

    Order the steps of an animal program:

  • Click in order

    Click the elements in the correct order:

  • Vertical ordering

    Order the text processing steps:

  1. Put in orderData Types - Ordering
  2. Put in orderType Conversion
  3. Put in orderMathematical Operations
  4. Put in orderConversion Process
  5. Put in orderTemperature Conversion Program
  6. Put in orderType Checking
  7. Coding taskType Checking
  8. Coding taskString → int Conversion
  9. Put in orderF-string
  10. Coding taskInteger Division vs Regular Division
  11. Coding taskString Slicing
  12. Click in orderBuilding type()
  13. QuestionThe int Type
  14. QuestionDivision
  15. Put in orderBMI Calculation
  16. QuestionModulo Operator
  17. QuestionBoolean Values
  18. Click in orderBuilding float()
  19. QuestionString Indexing
  20. Click in orderCreating a Variable
  21. Click in orderPrint with f-string
  22. Coding taskSafari Base Camp - Menu
  23. Coding taskSafari Base Camp - Input
  24. Put in orderint Conversion
  25. Coding taskSafari Base Camp - Calculator
  26. Coding taskSafari Base Camp - Journal
  27. Click in orderBuilding input()
  28. Coding taskSafari Base Camp - Complete Project
  29. QuestionSummary - Variables
  30. QuestionSummary - Types
  31. QuestionType Hierarchy
  32. QuestionSummary - Conversion
  33. QuestionSummary - F-strings
  34. Put in orderString Slicing
  35. Put in orderProgram with Multiple Variables
  36. Click in orderBuilding len()
  37. Put in orderProgram with Strings
  38. QuestionSummary - Print

Useful articles