DEV Community

Mark Edosa
Mark Edosa

Posted on • Edited on

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 like 2.3, 8.22.

  • You can perform arithmetic operations on integers and floats using + - * / %. For example: 2 + 2, 9 - 6, 8 * 3, 5 / 2 and 15 % 2.

  • Booleans such as True and False are used to influence the direction of flow of a program. False values include 0, '', [], {}, set().

  • Comparison operators (> < >= <= == !=) and logical operators (and or not) yield booleans. For 5 > 3 is True while 9 < 3 is False.

  • 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".
  • Common string methods include replace(), strip(), format(), lower(), upper() and title().

  • Check the type of a value with the type() function.

  • int(), float() and str() 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
Enter fullscreen mode Exit fullscreen mode

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 example print(height) will display 7.2 in the python console or REPL.

age and height 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.

Reserved 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

Enter fullscreen mode Exit fullscreen mode

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 and floats 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
Enter fullscreen mode Exit fullscreen mode
# use the variables
total_price = number_of_fish * amount # 104.0

# print(total_price)
# >>> total_price
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Quick Exercise
# what's the answer
100 >= 45
Enter fullscreen mode Exit fullscreen mode
number_1 = 45
number_2 = 67
number_1 <= number_2 # What's the answer?
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.
"""
Enter fullscreen mode Exit fullscreen mode

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"

Enter fullscreen mode Exit fullscreen mode

A way to correct the error above is to use the string escape character backslash \.

'john\'s paper'
"John\"s Paper"
Enter fullscreen mode Exit fullscreen mode

There are other escape characters such as the \n (newline character) and \t (tab character).

String Operations

Counting
len(address) # 26
Enter fullscreen mode Exit fullscreen mode
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'
Enter fullscreen mode Exit fullscreen mode
#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!'
Enter fullscreen mode Exit fullscreen mode
#4 using the * operator
name * 5 # 'John DoeJohn DoeJohn DoeJohn DoeJohn Doe'
Enter fullscreen mode Exit fullscreen mode
Indexing and Slicing
# indexing
# The letter in the 3rd position is 'h'
name[2] # 'h'
Enter fullscreen mode Exit fullscreen mode
#First position 
name[0] # 'J'

# last position
name[-1] # 'e'
Enter fullscreen mode Exit fullscreen mode
# 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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
# The original name is not affected
print(name) # 'John Doe'

# or
>>> name
'John Doe'
Enter fullscreen mode Exit fullscreen mode
# upper
name.upper() # 'JOHN DOE'

# lower
new_name.lower() # 'mary doe'
Enter fullscreen mode Exit fullscreen mode
# 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.'
Enter fullscreen mode Exit fullscreen mode
# 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'
Enter fullscreen mode Exit fullscreen mode

Types and Type Conversions

Types

In python, you can check the value type using the type() function. For example

type("a string") # <class 'str'>
Enter fullscreen mode Exit fullscreen mode
# we created the name variable above
type(name) # <class 'str'>
Enter fullscreen mode Exit fullscreen mode
type(age) # <class 'int'>
Enter fullscreen mode Exit fullscreen mode
# remember that height is a number that contains decimal places
type(height) # <class 'float'>
Enter fullscreen mode Exit fullscreen mode

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'>
Enter fullscreen mode Exit fullscreen mode

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() or float() 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() or float().

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)))
Enter fullscreen mode Exit fullscreen mode
my_string: '12.234'' is of type '<class 'str'>'
my_string_is_now_a_float: '12.234'' is of type '<class 'float'>'
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode
# convert integer to string
str(my_int) # '45'

# convert float to string
str(my_float) # '45.2'

Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)