Table of Contents



Data Types

Variables can store data of different types, and different data types serve different purposes. Python has the following data types built-in by default, in these categories:

Category Data Types
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview

In this section, we will discuss the most important basic data types:

  • int
  • float
  • str
  • bool

In the next section, we shall discuss the more advanced data structures: list, tuple, range, dict and set.

Integers and Floating-point Numbers

The data types int and float represent integers and floating-point numbers, respectively. We can understand floating-point numbers simply as decimals. To find out the data type of a given object, use the type() function.

Example

Type of an integer.

1type(5)
int

The above shows that the type of the number 5 is int.

Example

Type of a float.

1type(6.1)
float

This means that the type of the number 6.1 is float.

If you want to force a number to be a float instead of an int, use either a trailing decimal point or the float() constructor:

Example

Adding trailing decimal converts a number to float.

1type(5.)  # trailing decimal
float

Example

The float() constructor.

1type(float(5))  # float constructor
float

Conversely, Using the int() constructor, you can turn a float into an int. If the fractional part is not zero, it will be truncated.

Example

The int() constructor.

1int(6.8)  # turn a float into an int (truncated)
6
1type(int(6.8))  # type
int

Strings

We can understand strings simply as texts. In Python, strings can be expressed by using either double quotes (") or single quotes (’). The only condition is that you have to start and end the string with the same type of quotes.

Example

String in double quotes.

1str1 = "I am a string in double quotes."
2print(str1)
3type(str1)
I am a string in double quotes.

str

Example

String in single quotes.

1str2 = 'I am a string in single quotes.'
2print(str2)
3type(str2)
I am a string in single quotes.

str

You can use operator + to concatenate strings or * to repeat strings.

Example

Using + operator to concatenate two strings.

1"This is a course on " + 'Python.'  # concatenation
'This is a course on Python.'

Example

Using * operator to repeat a string.

1'This sentence is repeated 3 times. '*3  # repetition
'This sentence is repeated 3 times. This sentence is repeated 3 times. This sentence is repeated 3 times. '

ADVERTISEMENT



String Methods

The title() method changes each word to title case so that each word begins with a capital letter.

Example

title()

1name = "tom cruise"
2name.title()
'Tom Cruise'

Several other useful methods are available for dealing with case as well. For example, you can change a string to all uppercase or all lowercase letters using the upper() and lower() methods, respectively.

Example

Upper case.

1name = "Donald Trump"
2name.upper()
'DONALD TRUMP'

Example

Lower case.

1name.lower()
'donald trump'

Note that all string methods do not change the original string but instead return a new string with the changed attributes. In the above example, the original variable (name) remains unchanged.

1name
'Donald Trump'

To keep the changes, you can either assign the original variable to the new value or assign a new variable to the new value.

Example

Original variable name assigned to new object.

1name = "Donald Trump"
2name = name.upper()  # original variable name assigned to new object
3name
'DONALD TRUMP'

Example

New variable name assigned to new object.

1name = "Donald Trump"
2name1 = name.upper()  # new variable name assigned to new object
3name1
'DONALD TRUMP'

We can count the number of occurrences of a certain letter in a string using the count() method.

Example

count()

1word = "testimonial"
2word.count('t')   # count number of occurrences of 't'
2

Example

count() blank spaces.

1sentence = "Hello I am back!"
2sentence.count(" ") # count the number of blank spaces.
3

We can use the replace() method to make replacements in a string.

Example

replace()

1sentence.replace('back','here') # 'back' is replaced with 'here'
'Hello I am here!'

We can also split a sentence into a list of words.

Example

split() by space.

1sentence.split() # split by white space
['Hello', 'I', 'am', 'back!']

The above output is called a Python list which we will discuss in a later section.

👀 Preview

Example

split() by a letter.

1sentence.split("a") # split by a letter
['Hello I ', 'm b', 'ck!']

We can also check if the string starts with certain character(s).

Example

startswith()

1sentence.startswith("H")
True

Example

startswith()

1sentence.startswith("Hel")
True

Example

startswith()

1sentence.startswith("el")
False

Finally, we can employ the center() method to center a string to any specified length. For example, the following code returns a string with 50 characters, with the input string centered and missing space on each side filled with a specified character “=”.

Example

center()

1
2txt = "DigitalBlackboard"
3
4txt.center(50, "=") # returns a string with 50 characters with tex centered and
================DigitalBlackboard=================

The following table summarizes some of the most useful string methods.

Method Description
capitalize() Converts the first letter to upper case.
center() Returns a centered string.
count() Counts the number of occurrences of a certain letter.
startswith() Returns true if string starts with a specified letter.
endswith() Returns true if string ends with a specified letter.
find() Searches for a specified letter and returns the first position of where it is found.
isalnum() Returns True if all characters are alphanumeric.
isalpha() Returns True if all characters are alphabets.
islower() Returns True if all characters are lower case.
isupper() Returns True if all characters are upper case.
replace() Returns a string where a specified letter is replaced by another specified letter.
title() Converts the first letter of each word to upper case.
upper() Converts a string into upper case.
lower() Converts a string into lower case.

ADVERTISEMENT



Mixing Strings and Variables

If we want to mix strings with variables, we can employ f-strings, or formatted string literals. Simply put an f in front of your string and variables in between curly braces:

Example

f-strings

1year = 2016
2event = 'Election'
3f'Results of the {year} {event}'
'Results of the 2016 Election'

Example

We can also put mathematical expressions within the curly braces.

1bags = 3
2oranges_per_bag = 4
3f'We have a total of {bags*oranges_per_bag} oranges.'
'We have a total of 12 oranges.'

Example

f-strings.

1import math
2apples = 20
3bags = 6
4f'If we distribute {apples} apples to {bags} bags, we are left with {int(math.remainder(apples,bags))} apples.'
'If we distribute 20 apples to 6 bags, we are left with 2 apples.'

We can also have multiline f-Strings. But remember that you need to place an f in front of each line of a multiline string.

Example

Multiline f-Strings.

1name = "Julia"
2age = "28"
3country = "Singapore"
4message = (
5    f"Her name is {name}. "
6    f"Her age is {age} and "
7    f"she lives in {country}."
8)
9message
'Her name is Julia. Her age is 28 and she lives in Singapore.'

Indexing and Slicing Strings

We can check the size of the string by using the built-in function len().

Example

len()

1s="This is London"
2len(s) #including spaces
14

To access to specific elements of a string (which is a sequence of characters), we make use of indexing and slicing.

Indexing Strings

Python is zero index-based, which means that the first element in a sequence has an index of 0. Negative indices from -1 allow us to refer to elements from the end of the sequence.

Example

Index 0.

1country = "Singapore"
2country[0] # first element
'S'

Example

1country[1] #second element
'i'

Example

Negative index.

1country[-1] # first element from the end
'e'

Example

1country[-3] # third element from the end
'o'

Slicing Strings

If you want to get more than one element from a sequence, you can use the slicing syntax, which works as follows:

sequence[start:stop:step]

Parameter Description
start Optional (default=0). An integer number specifying at which position to start the slicing.
stop An integer number specifying at which position to end the slicing.
step Optional (default=1). An integer number specifying the step of the slicing.

Python uses half-open intervals: the start index is included while the stop index is not.

Let’s create a table of indices of the string “Singapore”.

Index 0 1 2 3 4 5 6 7 8
Negative Index -9 -8 -7 -6 -5 -4 -3 -2 -1
Character S i n g a p o r e

Example

Start index is not specified (default to 0).

1print(country)
2country[:2] # first 2 elements
Singapore

'Si'

Example

1country[1:4] # all elements from index 1 to 3
'ing'

Example

1country[2:] # all elements starting with index 2
'ngapore'

Example

Negative index slicing.

Negative Index -9 -8 -7 -6 -5 -4 -3 -2 -1
Character S i n g a p o r e
1country[-4:-1] # all elements from index -4 to -2
'por'

Example

Every second element.

Index 0 1 2 3 4 5 6 7 8
Character S i n g a p o r e
1country[::2] # every second element
'Snaoe'

Example

Negative step.

1country[::-1] # spelt backwards
'eropagniS'

Example

Negative step with range.

Negative Index -9 -8 -7 -6 -5 -4 -3 -2 -1
Character S i n g a p o r e
1country[-2:-5:-1] # all elements from index -2 to index -4 backwards
'rop'

Python also allows us to chain multiple index and slice operations together.

Example

Chaining slice operations.

Step 1:

Index 0 1 2 3 4 5 6 7 8
Character S i n g a p o r e

Step 2:

Index 0 1 2 3 4
Character S i n g a
1country[:5][2:]
'nga'

Example

Neat example.

1f'The 2-letter code of {country.title()} is {country.upper()[0] + country.upper()[3]}.'
'The 2-letter code of Singapore is SG.'

ADVERTISEMENT



Booleans

Boolean is another basic data type in Python. The Boolean values in Python are True or False.

The majority of objects in python are True, but there are some that evaluate to False including None, False, 0 or empty data types (e.g. empty strings).

Example

True

1type(True) # True is a Boolean type.
bool

Example

False

1type(False) # False is a Boolean type.
bool

Example

Boolean of a non-zero number.

1bool(1)
True

Example

Boolean of zero.

1bool(0)
False

Example

Boolean of False.

1bool(False)
False

Example

Boolean of None.

1bool(None) # None is a built-in constant and represents the absence of a value.
False

Example

Boolean of empty string.

1bool("") # empty string
False

Example

Boolean of non-empty string.

1bool("Hello World!")
True

Comparison Operators

Boolean expressions are expressions that yield Boolean values (i.e. True or False) using operators called Boolean operators. Boolean operators can be divided into

  • comparison operators
  • logical operators

We dicuss comparison operators in this section and logical operators in the next.

Comparison operators are used to compare values and evaluate the Boolean expression down to a single Boolean value (either True or False).

Example

Comparison operator: equivalent ==

11==2 # 1 equal to 2
False

Example

Comparison operator: greater than >

12>1 # 2 greater than 1
True

Example

Comparison operator: not equal !=

13!=4 # 3 not equal to 4
True

In the above examples, the comparison operators are ==, > and !=. The following table displays the complete list of Boolean comparison operators.

Operator Meaning Description
== Equal to results in True if the 2 operands are equal and False if unequal.
!= Not equal to results in True if the 2 operands are unequal and False if equal.
< Less than results in True if the first operand is smaller than the second, else a False.
> Greater than results in True if the first operand is greater than the second, else a False.
<= Less than or equal to results in True if the first operand is lesser than or equal to the second, else a False.
>= Greater than or equal to results in True if the first operand is greater than or equal to the second, else a False.

Note that Booleans are considered a numeric type in Python. True has a value of 1 and False has a value of 0.

Example

True has a value of 1.

1True == 1
True

Example

False has a value of 0.

1False == 0
True

Example

1True+True
2

Logical Operators

The logical operators in Python are: and, or and not. We can further divide them into

  • binary operators
  • unary operators

The operators and and or require 2 operands and are thus called binary operators. On the other hand, not is a unary operator which works on one operand.

Operator Meaning Type Usage
and True if both True Binary x and y
or True if at least 1 True Binary x or y
not True only if False Unary not x

Example

Binary and

1x=True
2y=False
3x and y # binary
False

Example

Binary or

1x or y # binary
True

Example

Unary not

1not x # unary
False

Example

Binary and

13>2 and 4<5
True