Python Data Types- The Definitive Guide

Python Data Types- The Definitive Guide

Strings and Numbers

In this article, we're going to look at some of the most frequently used python data types. data can be stored in memory in many different ways. Different computers may use different systems and terminology, but every programming language has to deal with the same trade-offs when it comes to choosing the right data type for the job. The Python programming language makes things a little simpler than most other programming languages, especially when it comes to working with its various data types. Although there are some subtleties that may catch the unwary programmer out, on the whole Python’s approach is straightforward and easy to understand. If you’re new to Python and thinking about starting to learn how to program in this programming language, then reading this article is a great way to get started. Here, we will explore the basics of Python data types and help you understand everything you need in order to get coding effectively today!

Overview of data types in python

Python Data Types are used to define the type of a variable. Every value in Python has a data type. Since everything is an object in Python programming, data types are actually classes, and variables are instance (object) of these classes. We will list out the data types and discuss the functionality of each.

The Importance of Data Types in Python

First of all, let’s take a look at the importance of data types in Python. Data types are crucial because they allow for Python to be very efficient. Since Python knows exactly what type of data it’s dealing with, it can make optimizations that allow for faster execution. Data types also allow for Python to be very secure. Since it knows exactly what type of data it’s dealing with, it can check that the data being sent from one location to another is of the correct type. This helps to eliminate data breaches and other security issues. If you are starting out in Python, don’t forget to first visit my first article on python variables. let us begin talking about python data types.

Strings

Assigning a value to a variable can be of different data types. In the course of programming with any programming language, it's of big priority to know the different data types used in that particular language. A string can be a character, text, a sentence or multiple of sentences enclosed in quotation marks. Think of a string as a sequence of characters. Let's begin using strings in our program.

#Create a variable called myString and pass on a string.

>>> myString ="some text"

#get the data type of the string using the type() function
>>> type(myString)
< class 'str'>

The type() function returns the data type of the string passed on. From the above, the class of the myString variable is 'str' which means string. Python is able to notice a string due to the quotation mark. Passing a number in quotation marks will be stored as a string

>>> myString = "44"

>>> type(myString)
<class 'str'>

The best way of storing numbers that are not used for calculation is storing them as strings such as invoice number or zip code.

Quotation mark uniformity

Uniformity of quotation mark is very crucial when using strings. When you start using single quotation mark( ' ' ), end with a single quotation mark but not double quotation mark( " " ). This rule is used when you wish to use quotation mark in your line of code.

>>> myString = "He said "meet me at 5""

## This code will return an error. 
## What this means is that python interpreter thinks this string ends at said" 
and does not understand anything afterwards.

When you want to use quotation marks in your string, it can be done this way by starting with a single quotation mark and using double quotation within the string.

>>> myString = 'She said "meet me at 5"'
>>> print(myString)
'she said "meet me at 5"'

String as a sequence of characters

In a string, every character has it's own index starting from 0. An index can be accessed by using braces [ ] and passing on the index you wish to print.

# using myString variable
>>> myString = 'She said "meet me at 5"'

# using the index to access characters in a string
>>> myString[0]
'S'

From the above, calling out index 0 returns the character S which starts the string we assigned to the variable myString. We can also get the index from the end of the string by using negative numbers. The last letter of a string is -1.

#This returns the last character of the string which is "
>>> myString[-1]
'"'

Empty spaces have index in a python string. Using the variable myString, index -3 from the string is an empty space.

#this returns an empty space

>>> myString[-3]
''

A string also has a length which is the number of characters in a particular string. We can get the length of a string by using the len() function.

>>> myString = 'She said "meet me at 5"'

>>> len(myString)
23

The last character of a string can also be determined by using it's length. The last character of a string is always the length-1

>>>myString[len(myString)-1]
'"'

The Slicing Technique

We can get a part of a string using slicing technique. Supposing you have a string that represents a bank account number where the first two characters indicate the country the account is from.

>>> bank_account= "GH1000095501"

To extract the country code of this account, it can be done using slicing. This is similar to getting an index but we employ colon. let's have an illustrative example

 >>> bank_account[0:2]
'GH'

As illustrated above, the first index is always included whereas the last index is excluded. Python interpreter reads the index from 0 to 1 without including 2.

Slicing from right to left

Assuming from our bank account, the country code is at the end of the account number. How do we write a code to get the country code using the slice technique? Let's have an illustrative example.

#placing the country code at the end
>>> bank_account= '1000095501GH'
'1000095501GH'
>>> bank_account[-2:]
'GH'
>>> bank_account[-2:-1]
'G'
>>> bank_account[-5:]
'501GH'

Counting index from right to left begins from -1 , -2 , -3 ...........

Operation that can be used with strings

Concatenation is the process of appending one string to another string. We can perform string concatenation using following ways:

Using '+' operator

This is the most simple way of string concatenation. Two strings can be concatenated in Python by simply using the ‘+’ operator between them. Let’s look at a simple example.

>>> "Hello" + "world"
'Helloworld'
>>> "Hello" + 2314
Traceback (most recent call last):
  File "<input>", line 1, in 
TypeError: can only concatenate str (not "int") to str

NB

Be careful of the data type you concatenate with a string. Strings can not be concatenated with numbers unless they are converted to strings using the str() function. We can use str() function to get the string representation of an object.

>>> "user" + str(231)
'user231'

using join() function

We can use join() function to concatenate strings with a separator. This is useful when we have a sequence of elements, for example list or tuple of strings. If you don’t want a separator, then use join() function with an empty string.

Screen.png

Using % operator

We can use the % operator to combine two strings in Python. Its implementation is shown in the example below.

ppp.png The %s denotes string data type. The space between the two strings in the output depends on the space between “%s %s”, which is clear from the example above.

Numbers

There are two data types to represent numbers and they are float and integer. There are not much differences between them besides the first(float) having decimals. Operations performed on both float and integer are the same. Python converts integer to float automatically when an operation results in a number with decimal.

# create two variables
>>> num1= 4
>>> num2= 3
# getting the data type of the variable 
>>> type(num1)
<'class 'int'>
# performing operation on the two variables
>>> result= num1 / num2
>>> print(result)
1.33333333333333
>>> type(result)
<class 'float'>

As you can see, these two data types can work together. You don't need to worry if your variable is an integer or float number. Most programming languages do not make these extinctions like java script where there is only one data type called number.

NB

  1. Avoid using comma to separate numbers, we only use dot
  2. Never use the thousand separator( eg. 1,004,567,000).

Operation that we can do with numbers

We have a fair idea of mathematical operations that can be done using numbers from mathematics. These same operators apply to numbers in python.

matttt.png There are some built in functions that can be applied to numbers.

round() function

We can use the round () to round any number with decimals When one argument is passed i.e the number you wish to round, it returns an integer. We can also pass two arguments i.e the number you wish to round and the number of decimal places.

>>> round(2.6784)
3
>>> round(2.6784 , 2)
2.68

Complex operations with numbers

In Python, complex math operation like Logarithmic and trigonometric functions can be done by importing modules in order to extend our possibilities. In order to use these function, call out the math module which comes with python installation. Inside this math module, there are hundreds of math functions we can use.

>>> import math
>>> math.factorial(5)
120
# runing up or down a number using ceil() and floor() functions
>>> math.ceil(2.3)
2
>>> math.floor(3.8)
3
>>> math.log(20)
2.995732273553991
>>> math.pi
3.141592653589793

To know more about math module, go to python modules

Conclusion

At the beginning of this article, we talked about how different computers may use different systems and terminology when referring to data types. However, Python’s approach is fairly straightforward and easy to understand for most programmers. Now that you understand strings and numbers data types, you can start coding using Python. However, keep in mind that there are some subtleties that may catch the unwary programmer out. Make sure to understand how the different data types work and you’ll be fine!