Python Tutorial Chapter #2: Basic Data Types

In Python, there are several built-in data types that you can use to store and manipulate data. In this tutorial, we will cover the following data types:

Python Tutorial Chapter #2: Basic Data Types
Python Tutorial Chapter #2: Basic Data Types

  • Integers: Integers are whole numbers that can be positive, negative, or zero. In Python, you can create an integer by assigning an integer value to a variable. For example:
    x = 5
    y = -10
    z = 0
    view raw integers.py hosted with ❤ by GitHub
  • Floats: Floats are numbers with decimal points. In Python, you can create a float by assigning a float value to a variable. For example:
    a = 3.14
    b = -2.718
    c = 0.0
    view raw float.py hosted with ❤ by GitHub
  • Strings: Strings are sequences of characters. In Python, you can create a string by enclosing a sequence of characters in quotation marks. You can use single quotes or double quotes, but you must use the same type of quotes to start and end the string. For example:
    s = "hello"
    t = 'world'
    view raw string.py hosted with ❤ by GitHub
  • Lists: Lists are ordered collections of items. In Python, you can create a list by enclosing a comma-separated list of items in square brackets. Lists can contain items of any data type, and the items do not have to be of the same data type. For example:
    l = [1, 2, 3]
    m = ['a', 'b', 'c']
    n = [1, 2.0, 'three']
    view raw lists.py hosted with ❤ by GitHub
  • Tuples: Tuples are similar to lists, but they are immutable, meaning that you cannot change the items in a tuple once it has been created. In Python, you can create a tuple by enclosing a comma-separated list of items in parentheses. Tuples can contain items of any data type, and the items do not have to be of the same data type. For example:
    t = (1, 2, 3)
    u = ('a', 'b', 'c')
    v = (1, 2.0, 'three')
    view raw tuples.py hosted with ❤ by GitHub
  • Dictionaries: Dictionaries are unordered collections of key-value pairs. In Python, you can create a dictionary by enclosing a comma-separated list of key-value pairs in curly braces. The keys and values can be of any data type. For example:
    d = {'a': 1, 'b': 2, 'c': 3}
    e = {1: 'one', 2: 'two', 3: 'three'}
    f = {'a': 1, 2: 'two', 3.0: 'three'}
    view raw dictionary.py hosted with ❤ by GitHub
Here are some examples of how you can use these data types in Python:
# accessing elements of a list
l = [1, 2, 3]
print(l[0]) # 1
print(l[1]) # 2
print(l[2]) # 3
# accessing elements of a tuple
t = (1, 2, 3)
print(t[0]) # 1
print(t[1]) # 2
print(t[2]) # 3
# accessing elements of a dictionary
d = {'a': 1, 'b': 2, 'c': 3}
print(d['a']) # 1
print(d['b']) # 2
print(d['c']) # 3