Introduction to Python Programming - Data Types and Operators
TLDR
-
Numeric types are either by nature whole numbers like
1, 2, 3
) or contain decimal places like2.3, 8.22
. -
You can perform arithmetic operations on integers and floats using
+ - * / %
. For example:2 + 2
,9 - 6
,8 * 3
,5 / 2
and15 % 2
. -
Booleans such as
True
andFalse
are used to influence the direction of flow of a program. False values include0, '', [], {}, set()
. -
Comparison operators (
> < >= <= == !=
) and logical operators (and or not
) yield booleans. For5 > 3
isTrue
while9 < 3
isFalse
. -
Strings are immutable sequences of characters enclosed in single or double quotes. Examples include
"Mary Doe"
,'John Doe'
, and so on. -
Common string operations include
- concatenation e.g.
"John " + "Doe"
gives"John Doe"
, - indexing e.g.
"John Doe"[0]
returns'J'
and"John Doe"[-1]
returns'e'
and - slicing, for example,
"John Doe"[0:3]
returns"Joh"
.
- concatenation e.g.
-
Common string methods include
replace()
,strip()
,format()
,lower()
,upper()
andtitle()
. -
Check the type of a value with the
type()
function. -
int()
,float()
andstr()
can be used for basic type conversions.
Data Types
The basic data or value types in python are integers, floats, booleans, and strings. These types are often written literally or stored in variables. Behind the scenes, memory is allocated whenever these types are created in a python program.
There is a type
None
which represents the absence of a value.
Integers and Floats
In python, numbers might be whole (integers) or might contain decimal places (floats). You can use these types to represent attributes like age, height, and weight and concepts like temperature, price, and so on. Addition information can be found here.
Creation
You can type the number literally. For example, 15, 23, 56
, etc., or use the int()
or float()
function (more on this later).
# Age in years
age = 54
# let's say height in feet
height = 7.2
The line beginning with # is called a comment. Python ignores it. So you can use it to document your code for yourself and others.
To run the code, you can either copy and paste it into a python shell or file. If you used a python file, you need to use the
print()
function to see the output. For exampleprint(height)
will display7.2
in the python console or REPL.
age
andheight
above are called variables. A variable is a symbol that represents a python data type. Think of it like an address to a house (data type). To create a variable in python, use the assignment operator (=
).
A variable's value can change throughout the program. So, we say python is dynamically-typed.
Certain rules apply when naming python variables. For example, python variables cannot start with numbers and can not be any of the reserved keywords. Use
help("keywords")
to see a list of researched keywords.
Check out this post for more information.
Operations
The most basic operation we perform with these types is arithmetic operations such as addition, subtraction, multiplication, and division. For example:
# Addition (with the + operator)
2 + 6 # 8
# Subtraction
6 - 5 # 1
# Multiplication
4 * 9 # 36
# Division
9 / 2 # 4.5
9 / 3 # 3.0
# Remainder division
8 % 3 # The remainder of 8/3 is 2
# Floor division
9 // 2 # 4
The arithmetic operators include
+, -, *, /, %
. The modulo (%
) operator does remainder division. For example, you can check if a number is even or odd or a multiple of 5 and so on.
To use the
integers
andfloats
in several places and to communicate your intent, you need to give them a name or assign them to a variable. This use of variables applies to every other data type.
# create two variables
number_of_fish = 20
amount = 5.2
# use the variables
total_price = number_of_fish * amount # 104.0
# print(total_price)
# >>> total_price
Boolean Data Type
Booleans represent the truthiness of a value. Simply, True
and False
Creation
#1 By literal boolean assignment
is_sweet = True
is_bitter = False
#2 From the result of a comparison or logical operation
# comparison
three_is_bigger_than_2 = 3 > 2 # True
is_bitter and is_sweet # False
Operations
The comparison operators include equal (==
), not equal (!=
), less than (<
), greater-than (>
), greater than or equal (>=
), and less than or equal (<=
). For example
3 == 3 # True, 3 is indeed equal to 3
6 != 7 # True, 6 is not equal to 7
8 > 18 # False, 8 is not greater than 18
2 < 10 # True, 2 is less than 10
Quick Exercise
# what's the answer
100 >= 45
number_1 = 45
number_2 = 67
number_1 <= number_2 # What's the answer?
The logical operators include and
, or
, and not
. For an and
operation to be true, both sides or operands must be true.
AND Truth Table
True | False | |
---|---|---|
True | True | False |
False | False | False |
- True
and
True is True - True
and
False is False - False
and
True is False - False
and
False is False
For an or
operation to be true, one side (operand) only needs to be true.
OR Truth Table
True | False | |
---|---|---|
True | True | True |
False | True | False |
- True
or
True is True - True
or
False is True - False
or
True is True - False
or
False is False
is_sweet and is_bitter # False
is_sweet or is_bitter # True
Strings
A string is a set of characters (letters, numbers, and symbols) surrounded by single '
or double "
quotes.
Strings are useful for identifying and grouping items. Strings are
-
immutable - a new string is always created after any string operations. The original remains unchanged.
-
Strings are also ordered sequences - This means that each element or character in a string has a position or index. The first element has an index value of 0.
Creation
# using double quotes
name = "John Doe"
occupation = "Data analyst"
# using single quotes
address = 'somewhere beyond the earth'
# using triple quotes
"""
The triple quotes must be proud of themselves
They keep the new line.
"""
During the creation of nested strings (strings within strings), the inner quotes should be different from the outer quotes. For example
# correct
"John's Paper" # double outer, single inner
'John"s Paper' # single outer, double inner
# wrong
# Why this? Read about escaping strings or escape sequences. Google is your friend :)
'john's paper'
"John"s Paper"
A way to correct the error above is to use the string escape character backslash \
.
'john\'s paper'
"John\"s Paper"
There are other escape characters such as the
\n
(newline character) and\t
(tab character).
String Operations
Counting
len(address) # 26
Concatenation (adding strings)
#1 with the + operator
"Hello, my name is" + " " + name + "." + " I am a " + occupation + "!" # 'Hello my name is John Doe. I am a Data analyst!'
#2 placing string literals side by side
"Hello, my name is " "John" # 'Hello, my name is John'
#3. Using the string format method
"My name is {}, and I work as a {}. I live {}!".format(name, occupation, address)
# 'My name is John Doe, and I work as a Data analyst. I live somewhere beyond the earth!'
#4 using the * operator
name * 5 # 'John DoeJohn DoeJohn DoeJohn DoeJohn Doe'
Indexing and Slicing
# indexing
# The letter in the 3rd position is 'h'
name[2] # 'h'
#First position
name[0] # 'J'
# last position
name[-1] # 'e'
# Slicing
# take from 1st to 4th (exclude the 4th element at index 3)
name[0:3] # 'Joh'
# slice from 4th to the end
name[3:] # 'n Doe'
String methods
String methods can be accessed via the_string.method()
pattern. For example, use the replace()
method to replace certain characters within a string.
# replace 'Johh' with 'Mary'
new_name = name.replace("John", "Mary")
new_name # Mary Doe
# The original name is not affected
print(name) # 'John Doe'
# or
>>> name
'John Doe'
# upper
name.upper() # 'JOHN DOE'
# lower
new_name.lower() # 'mary doe'
# strip: removes leading and trailing whitespace
" This string has lots of space. So trim it. ".strip() # 'This string has lots of space. So trim it.'
# We can chain multiple methods: convert to uppercase and then replace 'DOE' with an empty string
# Then remove the extra white space and slice starting from position 1 to the end
# Then convert the slice to a title-case string
name.upper().replace('DOE', '').strip()[1: ].title() # 'Ohn'
Types and Type Conversions
Types
In python, you can check the value type using the type()
function. For example
type("a string") # <class 'str'>
# we created the name variable above
type(name) # <class 'str'>
type(age) # <class 'int'>
# remember that height is a number that contains decimal places
type(height) # <class 'float'>
Behind the scenes, integers, floats, and strings are classes. Therefore, they are represented as
<class type>
.
Type Conversions
To determine a variable or data type, use the type()
function. For example
# create some variables
my_int = 45
my_float = 45.2
my_string = "12.234"
# Check the types
type(my_int) # <class 'int'>
type(my_float) # <class 'float'>
type(my_string) # <class 'str'>
Use the int()
function to convert a value to an integer. Use float()
and str()
to convert a type to float and string respectively.
Note the
int()
orfloat()
function can fail if it receives a value it cannot convert (an invalid type)
The
input
function takes user input from the console and always returns a string. If you ask users for integers/floats such as age and amount, you should convert the values with the appropriate function, that is,int()
orfloat()
.
now_a_float = float(my_string)
print("my_string: '{}'' is of type '{}'".format(my_string, type(my_string)))
print("now_a_float: '{}'' is of type '{}'".format(now_a_float, type(now_a_float)))
my_string: '12.234'' is of type '<class 'str'>'
my_string_is_now_a_float: '12.234'' is of type '<class 'float'>'
# convert integer to float
float(my_int) # 45.0
# convert float to integer - the decimal place is lost
int(my_float) # 45
# convert float to integer - the decimal place is lost
int(my_string_is_now_a_float) # 12
# convert integer to string
str(my_int) # '45'
# convert float to string
str(my_float) # '45.2'
Summary
You have learned about the fundamental types of python and their operations. You also saw how to convert from one type to another. Thanks for reading!