Module 2

Table of Contents

2.2 Basic Datatypes

Simple Python Code

Enter 1 + 1 in the IDLE

>>> 1 + 1
2

In Python, 1 + 1 is called an expression. An expression can consist of values (such as 1), operators (such as +, -, *, /). You can also use paranthesis for grouping.

Some examples:

>>> 5 + 5
10
>>> 10 * 3 - 5
25
>>> (10 * 3 - 5) / 5
5
>>> 5 / 2
2.5

Data types in Python

Below is the list of important data types commonly used in Python.

  1. Booleans
  2. Numbers
  3. Strings
  4. Bytes
  5. Lists
  6. Tuples
  7. Sets
  8. Dictionaries

1. Booleans

A boolean has two values - True or False. These values are constants and can be used to assign or compare boolean values.

>>> condition = True
>>> if condition == True:
...     print("The condition is true.")
... else:
...     print("The condition is false.)
...
The condition is true

2. Numbers

Numbers are one of the most prominent Python data types. The basic data types for numbers in Python are integer and float. Python also introduces complex as a new type of number.

Key points:

  • The numbers in Python can be int, float or complex.
  • Python has a built-in function type() to determine the data type of a variable or a value.
  • In Python, you can add a "j" or "J" after a number to make it imaginary or complex.
>>> num = 2
>>> print(type(num))
>>> num = 3.0
>>> print(type(num))
>>> num = 3+5j
>>> print(type(num))

Some operations on numbers

With Python, you can also use the ** operator to calculate powers.

>>> 3 ** 2 
9
>>> 2 ** 7  
128

The equal sign (=) is used to assign a value to a variable.

>>> breadth = 5
>>> length = 5 * 2
>>> length * breadth
50

There are plenty of other operators you can use in Python expressions. The following table lists all the math operators in Python from highest to lowest precedence.

Operator Operation Use Case
** Exponent 3 ** 2
% Modulus/remainder 22 % 8
// Integer division/floored quotient 22 / 8
/ Division 22 / 7
* Multiplication 10 * 3
- Subtraction 7 - 5
+ Addition 10 + 2

3. Strings

Besides operating on numbers, you can also manipulate strings. Strings can be enclosed in single quotes ('...') or double quotes ("...")

\ can be used to escape quotes.

>>> 'Good Day!'
'Good Day!'
>>> 'Don\'t do that.'
"Don't do that."
>>> "Don't do that."
"Don't do that."

You can use raw strings by adding an r before the first quote if you don’t want characters prefaced by \ to be interpreted as special characters.

>>> print('C:\some\name') 
C:\some
ame
>>> print(r'C:\some\name') 
C:\some\name

For multiple lines you can use triple-quotes: """...""" or '''...'''.

print("""\
database: connect [OPTIONS]
     -user john                         
     -email john@gmail.com               
""")

You can concatenate two strings using the + operator.

>>> 'Alice' + 'Bob'
'AliceBob'

You can repeat the strings using * operator.

>>> 'mi' + 2 * 'si' + 'pi'
'misisipi'

Two or more string literals next to each other are automatically concatenated.

>>> 'Py' 'thon'
'Python'

You can break long strings using this feature.

>>> text = ('This is a multiple line text.' 
            'It has two sentences.')
>>> text
This is a multiple line text. It has two sentences.

Indexing in strings

Strings can be indexed with the first character having index 0. There is no separate character type; a character is simply a string of size one.

>>> word = 'Apple'
>>> word[0]
'A'
>> word[4]
'e'

Indices may also have negative numbers.

>>> word[-1]
'e'
>>> word[-3]
'p'

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring.

>>> word[0:2]
'Ap'
>>> word[2:4]
'ple'

Note that start is always included, and the end always excluded.

Slice indices have useful defaults.

  • An omitted first index defaults to zero
  • An omitted second index defaults to the size of the string being sliced.
>>> word[:2]
'Ap'
>>> word[3:]
'le'

Bytes

The byte is an immutable type in Python. It can store a sequence of bytes (each 8-bits) ranging from 0 to 255. Similar to an array, we can fetch the value of a single byte by using the index. But we can not modify the value.

Here are a few differences between a byte and the string.

  • Byte objects contain a sequence of bytes whereas the strings store sequence of characters.
  • The bytes are machine-readable objects whereas the strings are just in human-readable form.
  • Since the byte is machine-readable, so they can be directly stored to the disk. Whereas, the strings first need to encoded before getting on to the disk.
>>> # Make an empty bytes object (8-bit bytes)
>>> empty_object = bytes(16)
>>> print(type(empty_object))
< class 'bytes' >
>>> print(empty_object)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

« Prev Next »