As I continue my journey into becoming a developer, I am starting to see some patterns across languages, in my last article I started my journey on learning Python. We explained how Python was a interpreted language rather than a compiled on like GoLang and explained the differences, benefits and downsides between the two approaches. We touched briefly on the history of the language and worked through how to deploy the interpreter on both Windows and Linux. Finally we wrote two very simple programs, the defacto “helloWorld” and a very simple function or to give it is proper name an object. Today in this the second article in the series, we will start to look at the building blocks of the language.
The first thing that we need to discuss is that Python is an object-oriented programming language! It is a what now, you say?
What is an Object-Oriented programming language?
An object-oriented programming language is usually a high-level computer programming language that implements objects and their associated procedures within the programming context to create software programs.
So the next question is What is an Object?
In object-oriented programming (OOP), objects are the units of code that are derived from the process of designing a program. They are self-contained and contain both the programming routines/procedures and the data being processed. An Object may contain data, in the form of fields, often known as attributes, and code, in the form of procedures, often known as methods. As an analogy, a person is an object which has certain properties such as height, gender, age, etc. Real-world objects are used to model the state and behaviour of real-world entities in your application.
How is this different for a procedural programming language?
Object-oriented programming is based on the concept of objects, while procedural programming is based on a sequence of procedures or instructions. In object-oriented programming, the data and behaviour are encapsulated within objects, while in procedural programming, the data and behaviour are separated. For a deeper dive into this interesting side-cart have a read of this article on the askanydifference site titled “Object-Oriented vs Procedural Programming: Difference and Comparison”.
From the site mentioned above this table highlights the major approach differences.
Comparison Table | ||
Parameters of Comparison | Object-Oriented Programming | Procedural Programming |
Approach | Bottom-up approach | Top-Down approach |
Divided into | Objects | Functions |
Secure | More | Less |
Access Specifier | Yes | No |
Examples | Python, C++, Perl and PHP | GoLang, Pascal, Basic and C |
Variables and Types
Oh Variables, we know all about these, don’t we 😊.
Well once again not quite correct. As Python is a OOP language the first major difference is that Variables and their Type do not need to be declared before utilisation. Also very variable in Python is an Object
Python has several built-in data types, including:
- int: Integer numbers, e.g., 42, -7
- float: Floating-point numbers, e.g., 3.14, -0.001
- complex: A complex number is a number that has a real part and an imaginary part. An example of a complex number is 2 + 3j.
- str: Strings (text), e.g., “hello”, “world”
- bool: Booleans (True or False), e.g., True, False
- list: Ordered, mutable (changeable) sequences, e.g., [1, 2, 3]
- tuple: Ordered, immutable (unchangeable) sequences, e.g., (1, 2, 3)
- set: Unordered, mutable collections of unique items, e.g., {1, 2, 3}.
Everything looks pretty normal, lets have a deeper look into each particular type.
Numbers
There are three types of numbers, firstly the integer, this is a whole number it also support complex numbers.
myint = 13 print(myint)
running this simple script will just echo the number 13 (our integer) to stdout.
The second type of number is the float; this is a floating point number for example 3.142 or -7.126 (negative 7.126).
myfloat = 13.0 print(myfloat) myfloat = float(13) print(myfloat)
Again, we have used a very simple script to demonstrate this concept. You will notice that we have appeared to repeat our code; however, there is a subtle difference, line three we have declared “myfloat” with the type float and given it the integer of 13. When you run this script you should receive the following output.
Finally a complex number, this is a number that is made up of a real and known part and an imaginary part, this is a hard (hence the term complex) concept to understand, if you have ever done higher maths than you will be well aware of the concept. It is easier to show and tell than just tell so here is a simple script to explain 😊
# Creating a complex number z = 13 + 20j # Printing the real and imaginary parts print (z.real) print (z.imag)
This script creates a complex number z with the real part 3 and the imaginary part 4j. Then it prints the real and imaginary parts of the complex number. The output of this script will be:
Next we will move on the String manipulation
Strings
In Python a string is defined by enclosing the string in either single of double quotes. Using double quotes allows the easy inclusion of apostrophes into a string without python interpreting it as a termination quote. To simply prevent Python seeing a double quote in a string as an termination character use the single quotation to define the string. However, how do you manage a string that has both apostrophes and speech quotations? Let’s have a look at an example script.
#String Declared with a single quotation mystring = 'Single quotation marks' print(mystring) #String Declared with a double quotation mystring = "Double quotation marks" print(mystring) #How to handle apostrophes in a string mystring = "My advice is don't worry about apostrophes" print(mystring) #How to handle double quotes in a string mystring = 'But Steve said "I worry about single and double quotations in the same string"' print(mystring) #How to manage both apostrophes and double quotes, we use the backslash. mystring = 'To which Tom replied " I\'ve no worries about using both double and single quotations"' print(mystring) mystring = ‘Then Steve asked another question, “what happens if I need a backslash in my string”’ print(mystring) mystring = ‘Tom simply replied “that is simple, I \’ve created this simple demo. Here is a \\ in my string”’ print(mystring)
String manipulation seems relatively straight forward. With the simple “\” backslash character you can escape any special character, you can even escape the “\” backslash with a double “\\” backslash.
Running the above script results in the following output:
We can also add carriage returns by including (\n) immediately in front of the word where you need to newline to start and Unicode characters since Python 3 unicode has been considered literal so you can directly enter extended characters in your strings for example if you want to enter the word“L’Oréal” into a string you simply using \u and the desired uncode string.
myunicode = "L'Or\u00E9al, you're worth it" print(myunicode)
Running this script results in the following output:
For a much more indepth discussion on the relevant options available for string manipulation what a read of the python documentation on the subject.
Booleans
A boolean is a data type that can have one of two values: True or False. Booleans are often used in programming to represent logical values, such as whether a condition is true or false. They are also used in conditional statements (such as if statements) to determine which block of code should be executed based on whether a condition is true or false.
x = True y = False if x: print("x is true") if not y: print("y is false")
This script creates two boolean variables, x and y, and then uses them in two if statements. The first statement checks if x is true, and if it is, it prints “x is true”. The second statement checks if y is false (using the not operator), and if it is, it prints “y is false”.
Lists
You may find that a list looks very similar to an array, each can include any sort of variable, and as many variables as you want. As Python does not actually have any native built-in support for arrays therefore lists are used instead. In Python a List can also be iterated over in a straightforward manner. Here’s an example of how to construct a list.
mylist = [] append(1) append(2) append(3) print(mylist[0]) # prints 1 print(mylist[1]) # prints 2 print(mylist[2]) # prints 3 # prints out 1,2,3 for x in mylist: print(x)
This script creates an empty list called “mylist”. We then populate it with the integers 1,2 and 3 by using the “append()” method.
The next three lines use indexing to print out the first, second, and third elements of the list, not that even though the list starts a “1” our indexing starts at “0”. Finally, the we use a “for” loop iterates over each element in the list and prints it out. This results in the output:
If we attempt to call an index that does not actually exist Python will generate an error.
mylist = [1,2,3] print(mylist[4])
Above we can see the actually error message when we attempt to read the index 4 of our list of 3 entities.
Tuple
A tuple is a collection of ordered, immutable elements. This means that once a tuple is created, its contents cannot be changed. You may thing that Tuples are similar to lists and they are in concept but lists and be changed, to define a tuple you simply enclose the entities in parentheses rather than square brackets.
Here’s an example of creating a tuple:
my_tuple = (1, 2, 3) print(my_tuple[0]) # prints 1 print(my_tuple[1]) # prints 2 print(my_tuple[2]) # prints 3 for x in mytuple print(x)
When you run this script you should receive the following output:
sets
A “set” in Python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
Python’s built-in set type has the following characteristics:
- Sets are unordered.
- Set elements are unique. Therefore Duplicate elements are not allowed.
- A set itself may be modified, but the elements contained in the set must be of an immutable type.
The last statement appears a little confusing on first read, however it is related to the concept of mutable and immutable objects. The statement you provided means that while a set itself can be modified (i.e., elements can be added or removed), the elements contained in the set must be of an immutable type. This is because if an element in a set were mutable and its value were changed, the set would become inconsistent and could not be used as intended.
We create a set by placing all the elements inside curly braces {}, each separated by comma. What is interesting about a set is that it can have any number of items and they may be of different types (integer, float, tuple, string etc.). as a list is a mutable object it cannot be included. Here is our example script:
# Creating an empty set myset = set() # Adding elements to the set myset.add(1) myset.add(2) myset.add(3) print(myset)
Note that rather than creating a “for” loop or printing out individual elements we used the print command with the myset variable. Running this script results in the following output:
For completenss lets expand our myset.py script to include not only integers but also, strings and a tuple. To do this we add the following lines between line 5 and 6
myset.add = (“hello”) myset.add = (“world”) myset.add = (1,2,3)
When you run the modified script you will receive the following output. You can now see that out set contains integers, strings and a tuple.
The keen eyed amoungst you will have noticed that the output is not as you would expect based on the order of the script. this is because the data contained in a “set” is not ordered.
Slicing
Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists. The indices used for slicing are also zero-based. There are two variants of the slicing syntax: sequence [start:stop] and sequence [start:stop:step].
Here’s an example of slicing a list in Python:
mylist = [1, 2, 3, 4, 5] myslice = mylist[1:3] print(myslice)
Running this script will output:
You may have noticed that I did not mention slicing a “set”. This is because you cannot slice or index “sets” in Python due to them being an unordered collections of unique elements, and therefore there is no concept of an index or order.
If you attempt to slice a “set” you will receive an error similar to the below:
However, you can iterate over the elements of a set using a for loop or use other set methods to manipulate the set. If you need to slice a set-like object, you can convert it to a list first and then slice the list. Here’s an example:
myset = {1, 2, 3, 4, 5} mylist = list(myset) slicedlist = mylist[1:3] print(slicedlist)
Running this will output:
Doesn’t this mean that “Sets” are more trouble than they are they are worth? If you convert then to a list so that they become structured data, you lose many of the benefits of a “Set”, any potential duplicates will be removed and the data may physically change its order. Well no, this is a slightly more advanced concept than I wanted to introduce here, but it seems pertinent.
Sets are used in Python to store collections of unique elements. As we know they are unordered and unindexed, which means that they individual elements cannot be accessed due to the lack of a known index or position. However, sets have several advantages over other data types in Python:
- Sets are optimized for membership testing. You can use the in operator to check if an element is in a set.
- Sets are useful for removing duplicates from a sequence.
- Sets can be used to compute mathematical operations such as intersection, union, difference, and symmetric difference
The last To manipulate a “set” you can use set methods to manipulate the elements of a set. Here are some examples:
- add(element): Adds an element to the set.
- remove(element): Removes an element from the set. Raises a KeyError if the element is not in the set.
- discard(element): Removes an element from the set if it is present.
- pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.
- clear(): Removes all elements from the set.
You can also use set operations to manipulate sets. Here are some examples:
- union(other_set): Returns a new set with all elements from both sets.
- intersection(other_set): Returns a new set with only the elements that are in both sets.
- difference(other_set): Returns a new set with only the elements that are in the first set but not in the second.
- symmetric_difference(other_set): Returns a new set with only the elements that are in either of the sets but not in both.
We are not going to delve any deeper in to “set.methods” yet, we will leave them for a later article.
Summary
We have covered a lot of ground today discussing the differing variables and types available in Python, A lot of this information, is very similar to the concepts discussed in our Golang series, but already we are running into differences between the two languages, mainly surrounding Lists and Sets. In our next article we will look at basic operators, delve a deeper into string formatting and manipulation in Python