Python basics
  • Tutorial
  • Exercices
  • About
  1. Fundamentals
  2. 2-Data types
  • Introduction
    • Python
  • Fundamentals
    • 0-Basic Syntax
    • 1-Variables
    • 2-Data types
    • 3-Numbers
    • 4-Strings
    • 5-Lists
    • 6-Booleans
    • 7-Loops
    • 8-Functions
    • 9-Dictionary
  • Advanced
    • 10-Numpy
    • 11-Matplotlib
    • 12-DataFrame
  • CLI
    • Exercices
    • Solutions
  • Git
    • Git introduction
    • Git branch
    • Git exercices
  • SQL
    • SQL Exercices
    • SQL Solutions

On this page

  • Build-in Data Types
  • Type
  • Cast
  1. Fundamentals
  2. 2-Data types

2-Data types

Notebook

Link to the Google Colaboratory notebook: 2-Data types

Build-in Data Types

Variables can store different type of data and then act differently for each type.

Default Build-in types
Name Type
Text str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
None Type NoneType

Here is an example for each type:

str_example = "Evry" 
int_example, float_example, complex_examle = 1, 2.0, 3j
liste_example = ["Evry", "Courcouronnes"]
tuple_example = ("Evry", 77)
range_example = range(77)
map_example = {"Evry": 77}
set_example = {"France", "Italy", "Spain"}
frozenset_example = frozenset({"France", "Italy", "Spain"})
bool_example = True
binary_example = b"Evry"
byte_array_example = bytearray(5)
memory_view_example = memoryview(bytes(77))
none_type_example = None

Type

You can get the type of any variable using the type function:

x, name = 77, "Evry"
print(type(x), type(name))
<class 'int'> <class 'str'>

Cast

It is sometimes possible to convert a type to another.

To do so, you just need to pass the type name.

x = int(2.0) # convert a float into an integer
y = int("2") # convert a string into an integer

print(type(x), type(y))

z = float(1) # convert an integer to a float
a = float("1") # convert a string to a float

print(type(z), type(a))

name = str(77) # convert an integer to string
name_2 = str(2.3) # convert a float to string

print(type(name), type(name_2))
<class 'int'> <class 'int'>
<class 'float'> <class 'float'>
<class 'str'> <class 'str'>
1-Variables
3-Numbers
 

Copyright 2023, Clément Bernard