Made in Python

Most big software companies are language neutral, in other words, they don’t really care what programming language you are more comfortable with. Your recruiter will ask you what is your language of choice. This will be the programming language that you will have to write your code with. For this site I choose to use Python. Python is a high level, general-purpose programming language which was developed with emphases in code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java. Which means that code written in Python is easily readable and it takes less time to write. It seems a great choice for programming interviews.

It would be almost impossible to try to teach someone Python in one article. It is not the purpose of this site either. In this article we discuss some basics notions of Python, mainly for people who are familiar with other programming languages but need an explanation of some code that do not understand in this site. A new user to Python can notice a main difference to other programming languages like Java and C/C++, Python uses whitespace indentation, rather than curly braces or keywords, to delimit blocks of code. This article aims to include everything that someone would need to know about Python in order to understand the rest of the site. It assumes that the reader is somewhat familiar with programming.

Maybe the most basic command in every programming language after assigning values to variables is the for loop. This is where we start here, the structure of the for loop is “for i in object:”, the object can be a list, a string, a dictionary etc. In Python a very common keyword with the for loop is “range”, as we have an example in the following code. The range keyword has a difference between the two main versions of Python (version 2.7.x and 3.x). In the earlier version (2.7.x) the expression “range(2,11)” would create a list starting with the number 2, followed by all the numbers until 11 without including the last number (i.e. range(2,11) would be [2,3,4,5,6,7,8,9,10]). The expression “range(2,11)” in the later version of Python is a generator. A generator allows the generation of objects that are calculated when they are needed, they are not stored into memory beforehand. There are other differences with these two version for example 5/2 will result 2 in the 2.7.x version as it reads the numbers as integers (we need to type float(5)/2 to result 2.5) and Python in 3.x version will result 2.5 with the same code. From now on, we will use the newer version of Python.

for i in range(100):
    print(i)

List and dictionaries are important data structures that Python comes with. A list is a sequence of objects, in Python a list can contain objects of different types and elements of the list can be changed in the flow of the program. Moreover lists come with build in methods such as sort, append, remove, delete, etc. Dictionaries are hashmaps that store values attached to a key. The main benefit of dictionaries is really look up time of their elements, we will explain much more about hashmaps/dictionaries in a section later on. For now, we will only mention that they are unordered collections of elements.

Bellow we give some examples of basic Python syntax with an explanation as a comment (denoted by # in Python):

list_test = []                        # We denote a variable list_test and we assign to it  
                                      # the empty list []
list_test = [0, 'one', 2.0, 'one' ]   # We assign to the list_test list the list with the
                                      # elements 0 (int), 'one' (str), 2.0 (float), 'one' (str)
print(list_test[1])                   # This command will print 'one' to the screen, not that 
                                      # list start in the position 0
list_test.append('two')               # The append command will add the string 'two' at the 
                                      # end of the list_test list. Now the list_test will 
                                      # be [0, 'one', 2.0, 'one', 'two' ]
list_test[1:-1]                       # This command will return a copy of the list_test 
                                      # starting from the second element (index 1) up to the 
                                      # last element, i.e. ['one', 2.0, 'one' ]
[2,3,1,5,4].sort()                    # The sort operation sorts the given list, in this 
                                      # example will result to [1, 2, 3, 4, 5]
list_test.remove('one')               # The remove command finds the first instance of the 
                                      # given element and removes it, the resulting list 
                                      # is [0, 2.0, 'one', 'two']
del list_test[2]                      # This command deletes the element with the given 
                                      # index, the resulting list is [0, 2.0, 'two']

The above commands were some basic syntax for lists in Python. Now we give some basic syntax commands for dictionaries:

dict_test = {}                        # We assign to the variable dict_test the empty
                                      # dictionary {}
dict_test = {'k1': 13, 'k2': 7}       # We assign to the variable dict_test the 
                                      # dictionary {'k1': 13, 'k2': 7}, the first element 
                                      # is the key the element after : is the value
print(dict_test[ 'k2' ])              # This command prints 7, hence it is the value that 
                                      # corresponds to the key 'k2'
dict_test[ 'k3' ] = 17                # This command adds the key 'k3' with corresponding 
                                      # value 17, the resulting dictionary is 
                                      # {'k1': 13, 'k3': 17, 'k2': 7}
del dict_test['k2']                   # will remove the pair 'k2': 7 from the dictionary

Until now we have seen simple Python commands. Some more advanced commands in Python are very useful so we write them here.

a = [i for i in range(11) if i% 2 == 0]
a[1:-1]

The first line of the above code is called List Comprehension, the first line will assign a list to the variable a. The command [i for i in range(11) if i % 2 == 0]
will returns the list [0, 2, 4, 6, 8, 10], that is because we say to Python create a list with all values that are from 0 to 10 (‘for i in range(11)’) such that divided by 2 (‘if i%2==0’). The technique at the second line of the above code is called List Slicing. The syntax of list slicing is [start:end:stride], start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the space between items in the sliced list. For example, a stride of 2 would select every other item from the original list to place in the sliced list. The defaults for start is 0, end is end of list, and stride is 1. A negative stride number means that you go backwards, i.e. a[::-1] will return the reverse of a.

Some other basic and necessary command are if statement, while loops, and defining functions. The following code defines a function that uses all of these. The following code defines a function, fizzbuzz, which takes an input. When we run the fizzbuzz function it prints all the numbers from 1 up to the number one less than the input but prints a string instead if the number is divided by 3 or 5. If the number is divided by 5 and by 3 then it prints FizzBuzz (we don’t have to declare what is the input, Python automatically will assume that it is an integer), if it is divided by 5 and not divisible by 3 will print Buzz, it will print Fizz if it is divided by 3 but not 5, and it will print the current number otherwise.

def fizzbuzz(n):
    i = 1
    while i <= n:
        if (i % 5) == 0 and (i % 3) == 0:
            print("FizzBuzz")
        elif (i % 3) == 0:
            print("Fizz")
        elif (i % 5) == 0:
            print("Buzz")
        else:
            print(i)
        i = i + 1

fizzbuzz(16)

Python supports the object-oriented programming paradigm. Object is a data structure which contains data as well as methods, in other words we can wrap together variables and functions (now the functions are called methods). In the following example we see two special methods for Python and a normal one. The function named __init__ is the constructor of the object, this is the method that initialize the variables and run any other code that we need to run at the creation of the object. The other special function is __str__ which instructs Python what to print when we use the print function on this object. Finally, methods have always an additional input denoted by the keyword “self” (it works with any other name but by convention we use self), this is the first parameter from the inputs and it denotes the object itself. Object in Python can also inherit methods and variable by other objects, we will see example of this during code in later posts.

class person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "My name is " + self.name + " and my age is "+ str(self.age)

    def change_age(self, new_age):
        self.age = new_age

george = person ("George", 32)
print(george)
george.change_age(29)
print(george)

In this post we saw some basic elements of Python. Python uses whitespace to denote blocks of code instead of curly braces or keywords. There are two mainly used version of Python and we choose to use the latest one here. We mentioned some basic elements of Python, such as list, dictionaries, how to define functions, and how to create objects. All these are enough to get us started and any additional detail is given later.