Data Types and Operations#

Variables#

A variable is a placeholder for information that you want Python to recall later in the coding process when you need to complete an action. Technically, the variable acts as an address for where the data is stored in the memory.
Unlike languages, such as Java which are static typed, in Python there is no need to declare a variable or compile programs. The moment we assign a value to a variable, we create it. The data type of the variable is inferred from the value we assign to it when the program is executed. In addition, altering the data type of a previously declared variable is allowed in Python. For example, x = ‘apples’ can later become x = 5 in the same program. In the first case, the variable is of a string data type and in the second case it is an integer data type.
Based on the data type of the variable, the Python allocates memory and decides what can be stored in the memory and what operations can be performed on the stored piece of information.

# Example assigning a variable called x to 5
x = 5
print(x) # Outputs the value stored in the variable x
5

The print command outputs the value (5) of the variable x we created earlier to the console. Also note that anything followed by a pound sign (#) is not interpreted as code by the Python interpreter. It is treated as a comment. Comments are a good way to keep track of what the code does and it is meant for you or anyone that reads your code.

Data Types#

Data types are basically some attribute associated with a piece of data that tells the programming language about how to interpret its value and carry out operations or manipulations. For example, in English language we have data types such as word and number. The data types tell us how to interpret the value of some data that we might have, e.g., we can carry out multiplication for data of the type number but we cannot multiply data of the type word.
Python has various built-in (to be used out-of-the-box) data types such as Numbers, Strings, and Booleans

Numbers#

Number/Numeric data types store numeric values or numbers. Number objects are created when you assign a value to them.

var1 = 1 #initializing new variable var1
var2 = 10 #initializing new variable var2
print(var1, var2)
1 10

In the above line, we print the value stored in the variables that we had created earlier. In the code below, we will use the type command to check the data type of the stored variables.

type(var1)
int

Python supports different numerical types#

int (signed integers) - They are often just called integers or ints, are positive or negative whole numbers with no decimal point.

float (floating point real values) - Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10, e.g., 2.5e2 = 2.5 x 102 = 250.

complex (complex numbers) - are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b.

x = 5
type(x)
int
x = 17014118346046923173168730371588410572712
type(x)
int
x = 1.34763
type(x)
float
x = 5 + 2j
type(x)
complex

Operations on Numbers#

Python supports various operations on numerical data types. The following operations are supported:

Operation

Returns the (or gives the)

x + y

sum of variables x and y

x - y

difference of variables x and y

x * y

product of x and y

x / y

quotient of x and y

x // y

floored quotient of x and y

x % y

remained of x / y

-x

negated value of x

abs(x)

absolute value or magnitude of x

int(x)

converts x to an integer

float(x)

converts x to a float

complex(re, im)

creates a complex number with real part re and imaginary part im. im defaults to zero

x.conjugate()

conjugate of complex number x

divmod(x, y)

the pair (x // y, x % y)

pow(x, y)

x to the power y

x ** y

x to the power y

Lets try out all of the above things:

# Create two variables
x = 2
y = 5
# Add x and y
x + y
7
# Subtract y from x
x - y
-3
# Multiply x and y
x * y
10
# Divide y by x
y / x
2.5
# Floored division
y // x
2
# Remainder of division
y % x
1
# Divmod
divmod(y, x)
(2, 1)
# Negated x
-x
-2
# Absolute value
abs(-x)
2
# Convert x to float
x = float(x)
type(x)
float
# Conjugate of complex number
z = complex(x, y)
z.conjugate()
(2-5j)
# x to the power y
x ** y
32.0
# y to the power x
pow(y, x)
25.0
# NOTE: Converting from float to int discards the fractional part, be careful while using this. The opposite conversion is all okay.
x = 32.5
y = int(x)
print(x, y) # original value, converted value
32.5 32

Strings#

Text data in Python is handled as strings. Strings are basically collections of one or more characters put in a single quote, double quote, or triple quote. In python there is no character data type, a character is a string of length one.

var1 = "Hello World"
type(var1)
str
print(var1)
Hello World

NOTE: We had previously assigned a number to var1, but now we have changed it to a string. It is fine as long as we carry out the proper operations for the given data type when it is assigned to a given variable.

Operations on strings#

Length of strings#

One of the most widely used command is len. It provides the length of a string.

var1 = "Hello World"
len(var1)
11

Accessing values in strings#

As mentioned earlier, Python doesn’t support a character type; these are treated as strings of length one, thus also considered as substring. To access substrings, we use square brackets to slice a string along with an index to obtain the substring.

var1
'Hello World'
print(var1[0]) # Extracting the first letter from the string
H
print(var1[0:5]) #0, 1, 2, 3, 4
Hello

variable[startindex: endindex: step]

print(var1[0:5:2]) #0, 2, 4
Hlo
var1[:5] # same as var1[0:5]
'Hello'
var1[5:] # same as var1[5:10]
' World'
var1[-2] # get the second last character
'l'

NOTE: Python is a zero-indexed language, i.e., the index of items like strings starts at zero.

Updating strings#

You can “update” an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether.

var1
'Hello World'
print('Updated string :- ', var1[:6] + 'Python')
Updated string :-  Hello Python
var1
'Hello World'
var1 = var1[:6] + 'Python'
var1
'Hello Python'

String Formatting Operator#

One of Python’s coolest features is string formatting. This method allows us to create a string with certain unknown values dynamically.

print(f"1 + 2 is {1+2}")
1 + 2 is 3
var1 = "Python"
var2 = 1991
print(f"The programming language {var1} was first released in {var2}")
The programming language Python was first released in 1991
var1 = 10
var2 = 5  # some random variable
print(f"sum result: {var1 + var2}")
sum result: 15

Reverse string#

We can reverse a whole string by using [::-1]. Neat trick huh!

var1 = 'Python'
var1
'Python'
var1[::-1]
'nohtyP'
var1[6::-1]
'nohtyP'

The above operations are just some basic things that people routinely do with strings, there are a whole lot more things that you can do with them. Do check out the this link for more information.

Boolean#

A boolean data type is a special data type with one of two built-in values, True or False. Boolean objects that are equal to True are thuthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false.
NOTE: True and False with capital ‘T’ and ‘F’ are valid booleans otherwise Python will throw an error.

a = True
type(a)
bool

Statements are checked in python to return a boolean value. For example, we can use the command in to check the presence of a substring in a string. The return of that statement is a boolean. We can also check other numerical conditions using other operators such as <, >, or ==

'a' in 'python'
False
'p' in 'python'
True
10 < 5 # Returns false as 10 > 5
False
10 < 11 # Returns true
True
# For checking equality, we use a double equals sign as a single equal is used for assignment
type(10) == type(5)
True

Operations on Booleans#

There are three boolean operations that you can perform on this special data type.

Operation

Result

x or y

if x is true, then x, else y

x and y

if x is false, then x, else y

not x

if x is false, then True, else False

a = True
b = False
a or b
True
a and b
False
not a
False

Using these simple operations and statements, we can create powerful combinations of these variables and data types to check for complex conditions, as we will see later.

References:#

  1. https://docs.python.org/3/library/stdtypes.html

  2. https://www.futurelearn.com/info/courses/introduction-to-programming-with-python-fourth-rev-/0/steps/264867#:~:text=Python variables are simply containers,containers for storing data values.

  3. https://www.geeksforgeeks.org/python-data-types/

  4. https://www.baeldung.com/cs/statically-vs-dynamically-typed-languages