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:

1# Whole numbers - like the number of discovered species
2species_count = 42
3expedition_day = 7
4team_members = 5
5
6# Can be negative
7temperature_drop = -5
8depth_below_sea = -100
9
10# Python 3 supports very large numbers!
11huge_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:

1# Numbers with a decimal part
2temperature = 32.5
3humidity = 78.3
4distance_km = 15.7
5
6# Scientific notation
7speed_of_light = 3e8  # 3 * 10^8 = 300000000.0 (float!)
8tiny_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:

1# Text in single or double quotes
2explorer_name = "Darwin"
3location = 'Serengeti'
4
5# Multi-line strings (triple quotes)
6description = """
7This is a longer description
8spanning multiple lines
9of text.
10"""
11
12# Escape characters
13message = "Darwin said: \"Let's explore!\""
14path = "C:\\Users\\Darwin\\jungle"  # Windows path
15
16# Raw string (ignores escapes)
17path_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:

1# Only two values: True or False
2is_dangerous = True
3found_water = False
4is_raining = True
5
6# The result of a comparison is a bool
7temperature = 35
8is_hot = temperature > 30  # True
9
10age = 15
11is_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:

1# The type() function shows the variable's type
2species_count = 42
3print(type(species_count))  # <class 'int'>
4
5temperature = 32.5
6print(type(temperature))  # <class 'float'>
7
8name = "Darwin"
9print(type(name))  # <class 'str'>
10
11is_safe = True
12print(type(is_safe))  # <class 'bool'>
13
14# Practical use
15data = 42
16if type(data) == int:
17    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:

1# String → Int
2age_text = "25"
3age = int(age_text)
4print(age + 5)  # 30
5
6# String → Float
7temperature_text = "32.5"
8temperature = float(temperature_text)
9print(temperature + 2.5)  # 35.0
10
11# WARNING! Error if the string is not a number
12# bad_conversion = int("abc")  # ValueError!
13# int("42.5")  # also ValueError - int() does not accept a dot
14
15print(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:

1# Int → String
2species_count = 42
3count_text = str(species_count)
4print("Discovered " + count_text + " species")  # String concatenation
5
6# Float → String
7temperature = 32.5
8temp_text = str(temperature)
9message = 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:

1# Int → Float
2whole_number = 10
3decimal_number = float(whole_number)  # 10.0
4
5# Float → Int (truncates the decimal part!)
6decimal = 15.7
7whole = int(decimal)  # 15 (NOT 16!)
8
9decimal2 = 15.2
10whole2 = 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:

1# Numbers → Bool
2# 0 = False, all others = True
3print(bool(0))    # False
4print(bool(1))    # True
5print(bool(-5))   # True
6print(bool(100))  # True
7
8# String → Bool
9# Empty string = False, non-empty = True
10print(bool(""))       # False
11print(bool("Darwin")) # True
12print(bool(" "))      # True (a space is a character!)
13
14# Bool → Int
15print(int(True))   # 1
16print(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:

1# Basic operations
2a = 10
3b = 3
4
5print(a + b)   # 13 (addition)
6print(a - b)   # 7  (subtraction)
7print(a * b)   # 30 (multiplication)
8print(a / b)   # 3.333... (division - ALWAYS float!)
9print(a // b)  # 3 (floor division)
10print(a % b)   # 1 (remainder - modulo)
11print(a ** b)  # 1000 (exponentiation: 10^3)
12
13# Operations on floats
14x = 5.5
15y = 2.5
16print(x + y)   # 8.0
17print(x * y)   # 13.75
18
19# Mixing int and float → result is float
20mixed = 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:

1# Concatenation (joining)
2first_name = "Charles"
3last_name = "Darwin"
4full_name = first_name + " " + last_name
5print(full_name)  # Charles Darwin
6
7# Repetition
8jungle_cry = "Help! " * 3
9print(jungle_cry)  # Help! Help! Help!
10
11# String length
12name = "Darwin"
13print(len(name))  # 6
14
15# Indexing (from 0!)
16text = "Python"
17print(text[0])   # P
18print(text[1])   # y
19print(text[-1])  # n (last character)
20print(text.upper())  # PYTHON
21
22# Slicing
23word = "Expedition"
24print(word[0:4])   # Expe
25print(word[4:])    # dition
26print(word[:4])    # Expe
27print(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:

1# None - like an empty box
2treasure = None
3print(treasure)  # None
4print(type(treasure))  # <class 'NoneType'>
5
6# Practical use
7def find_species(name):
8    if name == "Python regius":
9        return "Found!"
10    return None  # Not found
11
12result = find_species("Unknown")
13if result is None:
14    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:

1print("=== Expedition Calculator ===\n")
2
3# Collecting data
4distance_text = input("Distance (km): ")
5time_text = input("Time (hours): ")
6team_size_text = input("Team size: ")
7
8# Converting to the appropriate types
9distance = float(distance_text)
10time = float(time_text)
11team_size = int(team_size_text)
12
13# Calculations
14avg_speed = distance / time
15distance_per_person = distance / team_size
16
17# Displaying results
18print("\n--- RESULTS ---")
19print(f"Average speed: {avg_speed:.2f} km/h")
20print(f"Distance per person: {distance_per_person:.2f} km")
21print(f"Type of distance: {type(distance)}")
22print(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
1# Fahrenheit to Celsius conversion calculator
2
3# TODO: Get the temperature in Fahrenheit
4fahrenheit = float(input("Temperature in Fahrenheit: "))
5
6# TODO: Calculate Celsius: C = (F - 32) x 5/9
7celsius = (fahrenheit - 32) * 5 / 9
8
9# TODO: Display the result
10print(f"{fahrenheit}°F = {celsius:.1f}°C")
11
12# TODO: Check if it's hot (>30), normal (15-30), or cold (<15)
13if celsius > 30:
14    print("Hot in the jungle!")
15elif celsius >= 15:
16    print("Pleasant temperature")
17else:
18    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.

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:

Useful articles