Skip to main content

URL shortener with python and flask - Chapter 2 - Let's play with python

In this chapter we will be brushing up our concepts in python. If you are good in python then you can skip this chapter and continue with the next one. But I recommend you to just skim through the contents of this chapter.
I am assuming that you already have python installed and the same is accessible from the command prompt. Now to get a hands on experience, open your IDLE or command prompt and start typing the code. Just remember that you will be typing line by line. As I am using Ipython notebook, we will see a little bit of variation from your output at some points. But the core concepts are the same.

To make sure that you are fully aware of using python, lets consider a code snippet
# This is a comment
# Python will not pay attention to this line
# print "Hello world" will print Hello world on the screen
print "Hello world"
Now on your interpreter, after you type # This is a comment press enter. Next after typing # Python will not pay attention to this line press enter again and so on until you get the end result, so that you will have a feel of what each and every line is doing in code.
If you are defining a function or a for loop or a while loop etc. then to indent your code you will have to use 4 spaces. In IDLE, the interpreter will automatically add 4 spaces, but in command prompt or terminal, we will have to add the spaces.
For more information visit: Interactive Mode
If you are not able to use python with the interpreter or command prompt then comment in the comment box and I will help you and make sure that you are able to run the code.

Printing your first statement

As printing is the first thing that is thought in any programming language, we will also start by printing "Hello world"
In [1]:
print "Hello world"
Hello world

Comments

We have successfully written a simple print statement above. Now you know what a print statement is and how to make python to print some text for you. But if some person who is new to python opens your code and thinks that the above print statement will print some text on a paper? That is the reason we need comments. Comments are text that is useful to the person who is seeing the code and python will neglect the text written inside the comment. You can comment as follows:
In [2]:
# This is a comment
# Python will not pay attention to this line
# print "Hello world" will print Hello world on the screen
print "Hello world"
Hello world

Arithmetic Operations with python

We can use python as a simple calculator. Python can do any arithmetic for you. But there is a little bit of magic. See it below
In [3]:
2+3
Out[3]:
5
In [4]:
5*10 # * means multiplication
Out[4]:
50
In [5]:
6/2 # division
Out[5]:
3
Till now everything is looking perfect. But when you divide 5 by 2 you will be expecting 2.5, but see what happens
In [6]:
5/2
Out[6]:
2
As you can see the output is just 2, but not 2.5. When there are two integers in the numerator and the denominator then we will only get integer as output. If you want python to give you accurate output then you should be adding a decimal in either numerator or denominator.
In [7]:
5.0/2 # decimal in the numerator
Out[7]:
2.5
In [8]:
5/2.0 # decimal in the denominator
Out[8]:
2.5
If you want to find the remainder, when one number is divided by another then you can use % operator.
In [9]:
5%2 # remainder
Out[9]:
1
To find the power of a number, then you can use ** operator
In [10]:
5**2 # ** means to find the power of a number
Out[10]:
25
Last but not the least, we have seen that / operator with both the integers will give you an integer. What if you are giving both decimal numbers, but want the output to be decimal? Yes you can use // operator for that case. See the following.
In [11]:
5.0//2.0 # strict integer division
Out[11]:
2.0
In mathematics we use BODMAS(Brackets Orders Division Multiplication Addition Subtraction) to evaluate an expression. I think it will be better if I can explain the above with an example. Consider the following example: $$(105 + 206) - 550 ÷ 5^{2} + 10$$ To find the value, according to BODMAS we should first consider Brackets - $(105 + 206) = 311$
Now the expression becomes $311 - 550 ÷ 5^{2} + 10$
As there are no more Brackets available in the expression we will continue with the Order - $5 ^ {2} = 25$
Expression now becomes $311 - 550 ÷ 25 + 10$
Up next in the queue is Division - $550 ÷ 25 = 22$
Expression is $311 - 22 + 10$
Multiplication - None so proceed for the next step
As Addition and Subtraction have equal importance we will evaluate the expression from Left to Right - $311 - 22 = 289$
$= 289 + 10 = 299$
So, $(105 + 206) - 550 ÷ 5^{2} + 10 = 299$
In a similar way in python we have operator precedence. Operator precedence in python is (), **, *, /, %, //, +, - (Brackets, Power of a number, multiplication, division, remainder of a number, floor division, addition, subtraction). Consider the following example:
In [12]:
-3**2 # Evaluated as -(3**2) not as (-3)**2
Out[12]:
-9
In [13]:
5.0/(2.0*10) # 2.0*10 is evaluated first
Out[13]:
0.25

Variables in python

If you have studied Algebra in mathematics you should have encountered this term Variable. In python Variables are used to store the values like width, length, age and so on. Variable as the name suggests stores values which can be changed from time to time and also if required, you can ask python to tell the value of the variable by giving its name.
Lets see an example.
Assume that we have to calculate the area of the rectangle. We know that width = 10units and height = 20units. As per mathematics we know that Area of the rectangle is width * height and so the value becomes 200units. We will do the same using python. Remember that = is used to assign a value to a given variable
In [14]:
width = 10 #units
height = 10 #units
area = width * height
print area #sq. units
100
In the above example width, height and area are variables. You can also print them individually!
So to be simple variables are useful when you want to name something. You can also give a name to a string.
In [15]:
my_name = "Anivarth Peesapati" # my name
print my_name
Anivarth Peesapati
If for example, for some reason you have changed your name and yes you can change the value of the my_name in python also. Let's do it
In [16]:
my_name = "Anivarth" # my name has been changed
print my_name
Anivarth
You can also assign variables to complex numbers.
In [17]:
complex_number = 5 + 9j
print complex_number
(5+9j)
Now you might be tempted to give some creative variable names. But don't waste your creativity here, there are some rules you will have to follow to give names to variables. Some of them are as follows:
  • Variable names should not start with a number.
  • It is okay to have number at the end or in the middle of the variable name.
  • Variable names should not contain any weird characters like *, -, / etc. except alphabets, numbers and _
  • Variable name should make sense. You cannot assign the value of James to Hubble!
  • You should not use any keywords like and, if, else, elif, or, while, for , while etc. to name a variable. All the reserved keywords can be seen from here: [Keywords](https://docs.python.org/2.5/ref/keywords.html)
You can learn more about these rules from here: PEP - 08,Python Naming Conventions.
Note: Variable names are case sensitive.

Strings

In python you can create strings using ' ' or " ". To create multiline strings you can use """ """ or ''' '''.
In [18]:
print 'Single line string 1' #single line string

print 'Single Line string 2' # single line string

print '''
This is a
multi
line string
''' # multi line string

print """
This is
again a multi
line string
""" # multi line string
Single line string 1
Single Line string 2

This is a
multi
line string


This is
again a multi
line string

To use ', " inside the strings you can use \ and this is called as escape sequence.
In [19]:
print 'Anivarth\'s Blog'
print '\\ is used to escape'
Anivarth's Blog
\ is used to escape
Some times you may want to use the string as it is. Then you can use python raw strings. Just add r in front of the string.
In [20]:
print r"Anivarth\'s Blog"
Anivarth\'s Blog
To join two strings you can use + and to multiply a string you can use *
In [21]:
first_name = "Anivarth"
last_name = "Peesapati"
print first_name +  last_name
print first_name * 3
AnivarthPeesapati
AnivarthAnivarthAnivarth

String Indexing and slicing

To print a character from a given string you can use string indexing.
In [22]:
print first_name[0] # should print "A"
A
In python the numbering starts from 0. So "A" - 0, "n" - 1 ...
You can also index the strings from the reverse side. But here the numbering starts from -1 but not 0.
In [23]:
print first_name[-1] # Should print h - last character in my first_name
h
To get a part of the string we will be using string slicing. Keep the following image for your reference.
In [24]:
prog_lang = "Python"
print prog_lang[0:4] # print "Pyth" and not including "o"
print prog_lang[-2:-6] # same as the above.
Pyth

Lists - Basics

If you go for shopping then you make a list of all the items that you want to purchase, or if you are a class teacher then you have a list of names of students or if you are a shop keeper then you have a list of all the products that you sell etc.
In a similar way you can make lists in python. You can create a list as follows:
In [25]:
items_to_purchase = ["Brush", "Razor", "Shirt", "Mouse"]
first_item = items_to_purchase[0]
print first_item
Brush
As you can see you can use Indexing and Slicing in a similar way we have used in strings.
You can also store numbers along with strings in lists. Or for that matter you can also store an another list inside a given list.
In [26]:
mixed_list = [1, "Brush", "Anivarth", 3, [3, "December"]]
You can change a particular element in a given list. To do so we will reference the element in the list by using list indexing and then use = to assign the value(In a similar way we have assigned a value to a variable).
In [27]:
mixed_list[1] = "Paste" # changing the value of a given element
print mixed_list # just printing the list
[1, 'Paste', 'Anivarth', 3, [3, 'December']]

Bool

Not to confuse you too much, Boolean is just True and False.
In boolean we have an important subset and and or. Of course we have XOR, NAND.... they are not really important as and, or
and, or literally mean the same with the english literature.
Consider that I am going for shopping and ...
  1. I will purchase a mobile phone.
  2. I will purchase a book.
Joining these two statements with and we get,
Statement I: I will purchase a mobile phone and I will purchase a book
means, if I don't purchase any one of the items then I am not satisfying the condition. Just speak out the statement I loudly and you can make sense.
Joining the two statements with or we get,
Statement II: I will purchase a mobile phone or I will purchase a book
Means, even if I don't purchase any one of the items then I am satisfying statement II or if I purchase both the items, even then I am satisfying the statement II. But I will not satisfy the condition if I will not purchase any of the items.
If I will purchase the item then we get True, otherwise we get False. If you are speaking out the sentence loudly then negate the statement to make it False. For example if you want to make Statement 1 as False then, I will not purchase a mobile phone is the negation.
So the truth table for and is as follows:
Statement 1 Statement 2 Statement 1 and Statement 2
True True True
True False False
False True False
False False False
Truth table for or is as follows:
Statement 1 Statement 2 Statement 1 or Statement 2
True True True
True False True
False True True
False False False

Decisions with if elif else

Some times you will have to take the decisions based on some conditions. You can do that using if-elif-else statement. Let us see an example.
In [28]:
# check if my name is James
if my_name == "James":
    # give 4 spaces of indent so
    # that python will understand
    # that this part of the code 
    # belongs to *if*
    print "Hi James"
# check if my names is Hubble
elif my_name == "Hubble":
    # this part belongs to *elif*
    print "Hello Hubble"
# check if my name is Robin
elif my_name == "Robin":
    # this part belongs to *elif*
    print "Hello Mr. Robin"
# if my name is not James or Hubble or Robin then:
else:
    # this part belongs to *else*
    print "Hello guest"
Hello guest
In the code above, in the if statement python checks if my_name is same as "James". But as per our recent executions my_name is "Anivarth", so this condition is not satisfied. Next in the elif statement python checks if my_name is equal to "Hubble", and yes its not, so this condition is not executed. Similarly the next elif statement fails. As none of the conditions has a truth, finally the else statement gets executed and so does it print "Hello guest".
Python starts from the if statement, then checks the elif and at the last comes to the else statement. If both elif statement and also else statement are true python will only execute the first truth statement it encounters and keeps quiet.
Indentation is a way to convey that the block of the code is a part of the parent above. You can learn more about indentation from Flow control in python - This one is python 3. Most of the code is same except that we use raw_input instead of input in python 2.
Also you can use any number of elifstatements but only one if and else statements respectively.
But this doesn't make sense right? Okay in the next example we will make decisions based on the user input.
REMEMBER that == is used for check if both the sides are equal or same. You can check variable with value or variable with variable and so on. > is used to check if the left side value is greater than the right side. < is used to check if the right side value is greater than the left side value. >= is used to check if left side value is greater than or equal to right side value. <= is used to check if right side value is greater than or equal to the left side value. All of these conditions and comparsions including in, not in , is , not is which we will be discussing later have the same priority.
In [29]:
# Program to check if the given number is even or odd.
#user input
user_input = raw_input("Please enter a number")

#convert user_input from string to a number
user_input_number = int(user_input)

#check if the number is even
if user_input_number % 2 == 0:
    print "Number is even"
else:
    print "Number is odd"
Please enter a number98
Number is even
When you give a string like "50", "60", "45", "78"...(condition is that they should have numbers and no other non sense), sending the value inside int() will convert the string to number. For example int("89") will make it 89. Rest of the code is simple.

Range

range(n) will give you a list of numbers starting from 0 to n-1
In [30]:
range(10) # range(stop)
Out[30]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can also specify the start as follows:
In [31]:
range(5, 10) # range(start, stop)
Out[31]:
[5, 6, 7, 8, 9]
And yes of course you can specify the interval in which the values have to be increased.
In [32]:
range(5, 20, 2) # range(start, stop, step)
Out[32]:
[5, 7, 9, 11, 13, 15, 17, 19]

For loop

If you remember your school days, your teacher would have given you an imposition to write a given paragraph or sentence 100 times probably. Now assume that you are the teacher and you will ask python to write a given sentence for some 5 times. Python completes the imposition within a fraction of second.
In [33]:
for i in range(5):
    print "I am writing an imposition"
I am writing an imposition
I am writing an imposition
I am writing an imposition
I am writing an imposition
I am writing an imposition
This is the use of the for loop. You can make python do the repetitive task for you by writing a few lines of code. Okay how does it work?
As you know range(5) will give you a list [0, 1, 2, 3, 4].
Iteration 1: Value of i = 0 and the print statement gets executed.
Iteration 2: Value of i = 1 and the print statement gets executed.
Iteration 3: Value of i = 2 and the print statement gets executed.
Iteration 4: Value of i = 3 and the print statement gets executed.
in derives its literal meaning from the english literature.
To check if we are correct, we will print i for each and every loop.
In [34]:
for i in range(5):
    print i
0
1
2
3
4
As you know from the previous example, when we used range we actually looped over a list. We can also loop through a list with some other elements and not just numbers.
In [35]:
for i in ["Anivarth", "Peesapati", "Python"]:
    print i
Anivarth
Peesapati
Python
Also remember that inside for loop you can add if, for.... statements as well.
You can learn more about for loops from here:

While loops

Till now we have seen for loops. Now we have an another loop called as while loop. You can use it alternatively with for loop. The main use of the while loop comes when you don't know the range in which you will have to loop through.
For example, if you were asked to print 500 multiples of 5 then you can use for loops. But if you were asked to find the 500th prime number then you may or may not know the number upto which you should loop.
while loop checks for a condition for each and every iteration and if the condition is satisfied then the loop progresses otherwise it terminates.
In [36]:
counter = 0
while counter < 6:
    print counter
    counter = counter + 1
0
1
2
3
4
5
Here, the function of i which we have used in the for loop is taken up by the counter.
Remember that you should increase the value of the counter also called the iterator for each and every iteration, otherwise you will end up in an infinite loop.
Learn more from here: More control flows

Functions

In mathematics or in any programming language a function as defined by Wikipedia is as follows:
In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output. An example is the function that relates each real number x to its square x2. The output of a function f corresponding to an input x is denoted by f(x) (read "f of x").
So as per the example given $f(x) = x^2$. Now the value of $f(3) = 3^2 = 9$
Functions are not just limited to one variable like $x$, but you can give as many variables as you want. But the corresponding expression may or may not contain both the variables. An example would be $f(x, y) = xy$ or $f(x, y) = x$
Functions in programming languages are mainly used to avoid repetition of code. Lets say you were asked to write an imposition of 3 different sentences for 3 times each.
Sentence 1: "Imposition 1"
Sentence 2: "Imposition 2"
Sentence 3: "Imposition 3"
With the present knowledge you may write the following code.
In [37]:
# imposition for statement 1
for i in range(3):
    print "Imposition 1"

# imposition for statement 2
i = 0
while i < 3:
    print "Imposition 2"
    i = i + 1

# imposition for statement 3
for i in range(3):
    print "Imposition 3"
Imposition 1
Imposition 1
Imposition 1
Imposition 2
Imposition 2
Imposition 2
Imposition 3
Imposition 3
Imposition 3
As you can see, in the above code we have a lot of duplication of the same for loop. To avoid this duplication we can use a function. Lets name the function imposition. It will look as follows:
In [38]:
# function to write a imposition
def imposition(sentence):
    for i in xrange(3):
        print sentence
def is the keyword used in python to create a function. The word followed by def is the name of the function(All the rules of variable naming convention apply). The variables in the parenthesis() are the input. Adding 4 spaces we add the block of the code that the function will do with the input.
Okay we will make use of the above imposition function to write impositions for three sentences.
In [39]:
sentence1 = "Imposition 1"
sentence2 = "Imposition 2"
sentence3 = "Imposition 3"

#impostion 1
imposition(sentence1)

# imposition 2
imposition(sentence2)

# imposition 3
imposition(sentence3)
Imposition 1
Imposition 1
Imposition 1
Imposition 2
Imposition 2
Imposition 2
Imposition 3
Imposition 3
Imposition 3
As you can see, it is very simple with functions.
Till now we have written a function which will print the given sentence for 3 times only. But what if your teacher changes her mind and gives you a sentence and instructs you to write the imposition for 5 times? As we have discussed above, we can define a function with more than one variable. We will extend our imposition function to take sentence and the number of times as input.
In [40]:
# imposition function extended
def imposition(sentence, num_times):
    """
    Function to print a sentence 
    for given num_times
    """
    for i in range(num_times):
        print sentence
We have used """ after the function definition. This is the function documentation and these strings are called as docstrings. It is just a comment and doesn't have any logic. You can learn more about function documentation from PEP257 - Docstrings python
This function will take two inputs
  1. Imposition sentence
  2. Number of times we have to write imposition.
You can call the function in many ways. But there are some rules.
  • Calling function directly without using the name of the variables
  • In this case you should not change the order in which you give the input. i.e. you should first enter the imposition sentence and the number. Doing it either way will raise an error.
In [41]:
# imposition function call
imposition("Imposition sentence", 5)
Imposition sentence
Imposition sentence
Imposition sentence
Imposition sentence
Imposition sentence
  • Calling the function using the variable names
  • In this case you can change the order and there is no problem.
In [42]:
# imposition function call with variables
imposition(num_times = 5, sentence = "I am learning python")
I am learning python
I am learning python
I am learning python
I am learning python
I am learning python

Default argument values in python

We have extended the function so that it can print the imposition sentence based on the mood of the teacher. But as a student of the class and having analysed her for so many days you know that she will usually give you imposition for 3 times and occasionally 5 times.
As you can see, to call the function we will have to give two inputs to the function what so ever may be the case. But as we know that our teacher will usually ask us to write imposition for 3 times, when defining the function we can give default values to the variable. So that if you will not give the input it will use the default value that you have given during the function definition. See the example below.
In [43]:
# function with default values
def imposition(sentence, num_times = 3):
    """
    This function will write imposition
    for you.
    """
    for i in range(num_times):
        print sentence
In [44]:
# using the default value of the function
imposition("This will be printed for 3 times")
This will be printed for 3 times
This will be printed for 3 times
This will be printed for 3 times
In [45]:
# teacher mood changes and print for 5 times
imposition("This will be printed 5 times", num_times = 5)
This will be printed 5 times
This will be printed 5 times
This will be printed 5 times
This will be printed 5 times
This will be printed 5 times

Functions that return a value

Sometimes there are functions, which will not print any stuff to the console, but will return a value, which can be used for further calculations. Lets say that we want to multiply three numbers and then add a number to the final value.
We will look at an example
In [46]:
# function that return a value
def multiplication(x, y, z):
    """
    This function will return the value 
    for further calculations
    """
    return x*y*z

# function that will not return a value
def multiplication_no_return(x, y, z):
    """
    This function will not return the value
    and thus cannot be used for further
    calculations
    """
    print x*y*z
In [47]:
# using the multiplication function for further calculations
print multiplication(1, 2, 3) + 5
11
In [48]:
# we cannot use the multiplication_no_return for any further calculations
# as there is a print statement already we can call it directly
multiplication_no_return(1, 2, 3)
6
You can see more examples of the return functions being used directly when we learn more about lists. But for now I suggest you reading about the return statement from follows:

Lambda expressions

Lambda expressions are used to create anonymous functions at a given point in the code. Anonymous functions will not have any name. They can be used in a [filter](https://docs.python.org/2/library/functions.html#filter), [reduce](https://docs.python.org/2/library/functions.html#reduce) etc..
You should have a look at following: Why are python lambdas useful?, Python Lambda functions
In [49]:
# some natural numbers
nat_num = range(20, 200)

# using the lambda expressions to find the multiples of 3
print filter(lambda x:x%3 == 0, nat_num)
[21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 189, 192, 195, 198]
filter function is an inbuilt function and will take two inputs. A function name or lambda expression and an iterable like lists.
In the above code filter function will churn out only the odd numbers.
You can also define a function with name using lambda expressions. We define the function similar to a variable. But it is recommended not to use lambda expressions for defining functions because the code will loose its readability. Anyways you can do it as follows:
In [50]:
# function to give the square of a number
g = lambda x: x**2

# calling the function
g(5)
Out[50]:
25
You can read more about functions from here: Defining functions

More on lists

Previously we have seen a little bit of basics of lists. But there are more operations that you can do with lists. Let us assume that the name of our list is ap = [1, 1, 2, 3, 4, 5].
  • ap.count(x) - Counts the number of times x has appeared in the list. So ap.count(1) is 2
  • ap.insert(i, x) - Inserts x at i in the list. So after calling ap.insert(2, 6), ap will become [1, 1, 6, 2, 3, 4, 5]
  • ap.append(x) - Appends x at the end of the list. So calling ap.append(7)will make ap [1, 1, 6, 2, 3, 4, 5, 7]
  • ap.index(x) - Will find the first position of the element x. So ap.index(1) will give 0, the first occurance of the element.
  • ap.remove(x) - Removes the first occurance of the element x. ap.remove(1) will make ap as [1, 6, 2, 3, 4, 5, 7].
  • ap.reverse() will reverse a given list. So ap.reverse() will make ap as [7, 5, 4, 3, 2, 6, 1]
  • ap.sort() - Sort the list in ascending order. So, ap.sort() will make the list as [1, 2, 3, 4, 5, 6, 7]
  • ap.pop() - Will remove the last element of the list. So, ap.pop() will return 7 and the list will become [1, 2, 3, 4, 5, 6]
Actually there are many ways to reverse a list. If you are interested, How to reverse a list in python
In [51]:
# our list
ap = [1, 1, 2, 3, 4, 5]

# counting - returns a value
print ap.count(1)

# inserting - does not return a value
ap.insert(2, 6)
print ap

# appending - does not return a value
ap.append(7)
print ap

# indexing - returns a value
print ap.index(1)

# remove - doesn't return a value
ap.remove(1)
print ap

# reverse - doesn't return a value
ap.reverse()
print ap

# sort - doesn't return a value
ap.sort()
print ap

# pop - returns a value
print ap.pop()
print ap
2
[1, 1, 6, 2, 3, 4, 5]
[1, 1, 6, 2, 3, 4, 5, 7]
0
[1, 6, 2, 3, 4, 5, 7]
[7, 5, 4, 3, 2, 6, 1]
[1, 2, 3, 4, 5, 6, 7]
7
[1, 2, 3, 4, 5, 6]

list comprehension

We can manipulate the items in the list by using a list comprehension. You can see the example below.
More about List comprehension Data Structures - Python, Python List comprehensions
In [52]:
# natural numbers
foo = range(20)

# squaring the number in the list
foo = [x**2 for x in foo]

print foo
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

Tuples

Tuples are list type objects but once the values are assigned to a tuple or to be simple once the tuple is created you cannot change the values inside. They are defined using ().
In [53]:
# creating a tuple
tup = (1, 2, 3)

# trying to manupulate the values
tup[1] = 3 # error!!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-eba5e1eebd67> in <module>()
      3 
      4 # trying to manupulate the values
----> 5 tup[1] = 3 # error!!

TypeError: 'tuple' object does not support item assignment
I know that you are confused. You can learn more about the differences between tuples and lists from the below.
What is the difference between lists and tuples, Understanding Tuples vs lists in python, Python tuples are not just constant lists.

Sets

Sets are an unordered collection of unique objects. They are similar to the ones which we use in mathematics. We can perform union, intersection, difference etc. A set is defined using {} or set() , but to create empty sets we have to use set() and cannot use {}(see dictionaries). List comprehensions can also be used for sets.
In [54]:
shopping_cart = {'apple', 'razor', 'mobile', 'brinjal', 'carrot', 'apple'}
print shopping_cart
set(['mobile', 'razor', 'carrot', 'apple', 'brinjal'])
As you can see, even though we have added apple two times to the cart, the duplicate is removed. Also the order is not followed. As part of illustration we will create a function which will find the difference of two sets and union of two sets.
Further reference: Sets - Unordered collection
In [55]:
# set A
A = {1, 2, 3, 4, 5}
B = {5, 9, 0, 4, 10}

# union
print A.union(B)

# difference
print A - B
set([0, 1, 2, 3, 4, 5, 9, 10])
set([1, 2, 3])

Dictionaries

Till now we have been indexing the elements in the list using numbers. For example to print the second element of a list with name ap we will use print ap[1]. But sometimes it would be very hard to remember the places at which the elements are situated. Then you can use dictionaries. I have only stated one very frequently experienced example, but there are many ways you can use dictionaries.
Dictionaries have key value pairs and you will index the element using key name. Similar to sets dictionaries doesn't have any order priority and they are unordered.
You can define a dictionary using {}, dict(). You can use any one for creating empty dictionaries also.
We know that in a class, every student has a roll number. Recently our teacher conducted a quiz and stored the quiz marks in a list according to the roll number(Assume that roll numbers of our class starts with 0). Every time she wants to see the marks of a particular student, she is opening the register book and checking the roll number of the student and then indexing the marks in the list. It was easy for her last year as there were only 2 students. But this year as there are 5 students she is always getting confused.
According to me, she should start using dictionaries. Here is the example of our class using dictionaries.
In [56]:
# marks of the students
marks = {'anivarth':5, 'jack':3, 'jones':4, 'robin':2.5, 'miller':4.5}

# defining the marks using dict()
marks = dict(anivarth=5, jack=3, jones=4, robin=2.5, miller=4.5)

# an another way using tuples and lists
marks = dict([('anivarth', 5), ('jack', 3), ('jones', 4), ('robin', 2.5), ('miller', 4.5)])
In [57]:
# marks of anivarth
print marks['anivarth']
5
As you can see, using dictionaries it is very easy to index a particular element. In a dictionary key can be a string or a number(can be int or float) but the value can be anything. You can even use the variable names.
The only exception is using the dict() function directly. In this case we will not use strings for the keys but we will define them directly.
Each of the methods for creating the dictionaries is one and the same.
We will print the keys and values of our dict separately.
In [58]:
print marks.keys()
print marks.values()
['jones', 'anivarth', 'jack', 'miller', 'robin']
[4, 5, 3, 4.5, 2.5]
Our teacher is very strict and doesn't want a student whose marks are less than 3. She will remove her from the name from the register. She can do that as follows:
In [59]:
del marks['robin']
print marks
{'jones': 4, 'anivarth': 5, 'jack': 3, 'miller': 4.5}
We can also use list comprehensions in dictionaries.
In [60]:
squares = {x:x**2 for x in range(10)}
print squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
You can read more about these data structures(Lists, Tuples, Dicts, etc) from Data Structures

Modules

Till now we have seen functions. With python the biggest advantage is that you can define a function in a file and import and use it forever. You can also define your list or variable or anything that is python and use it.
Okay lets create a simple module that will print the Fibonacci numbers.
I am assuming that you are using IDLE editor. Click File > New File.
In the new file that opens type the following function or any function you want.
In [61]:
def fib(n):
    """
    This function will print
    fibonacci numbers upto n
    """
    a = 0
    b = 1
    while b < n:
        print b
        temp = a
        a = b
        b = temp + a
Now save the file at a location you want and let the name of the file be fibo.py
To make use of this function in our next project we will have to import the file.
We can use import to import a given file. But it will not work if you have saved the file somewhere on desktop or documents etc. Because python will search for the file in the directories that python actually is used to. To import file from some other location we have to use sys. This one is inbuilt and is in the form of a file. We can import this file directly because python is aware of the directory in which this file resides.
In [62]:
# importing sys module
import sys

# directories that python checks for
print sys.path
['', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\python27.zip', 'C:\\Program Files\\FreeCAD 0.16\\bin', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\DLLs', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\plat-win', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\lib-tk', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\site-packages', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\site-packages\\setuptools-27.2.0-py2.7.egg', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\SEKHAR PEESAPATI\\.ipython']
As you can see, depending on your configuration, python will search for the files in the following directories. But how do we add our directory to this list?
If you remember the append that we have discussed, you can use it to append custom directory to the list. Okay I will add my desktop to the list.
In [63]:
# appending a directory to the list
sys.path.append("C:\\users\\sekhar peesapati\\desktop")

# checking if the directory is added
print sys.path
['', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\python27.zip', 'C:\\Program Files\\FreeCAD 0.16\\bin', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\DLLs', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\plat-win', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\lib-tk', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\site-packages', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\site-packages\\setuptools-27.2.0-py2.7.egg', 'C:\\Users\\SEKHAR PEESAPATI\\Anaconda3\\envs\\ipykernel_py2\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\SEKHAR PEESAPATI\\.ipython', 'C:\\users\\sekhar peesapati\\desktop']
In [64]:
# importing our module
import fibo

# using the function in our module
fibo.fib(10)
1
1
2
3
5
8
In the second line, fibo is the file name and fib is the function name.
You can import a particular function from the file.
In [65]:
# importing fib from fibo
from fibo import fib

# using the fib function
fib(15)
1
1
2
3
5
8
13
If there are more than one function and I know that it would be a daunting task to write the names of each and every function. You can import all the function at a time as follows.
In [66]:
# importing all the functions
from fibo import *

# using the fib function
fib(8)
1
1
2
3
5
As you can see, modules has a lot of advantages. We can use the files of our friends or files of the community. This will help us save a lot of time. Python has a lot of inbuilt modules and you can see all the modules using dir().
One of the modules that is used very frequently is the math module.
In [67]:
# importing math module
import math

# find the sine of a number
math.sin(50)
Out[67]:
-0.26237485370392877
Collections of modules are called a package and modules is a very important concept in python. My suggestion is that you spend some time understanding these concepts as much as you can.
More on modules from here: Modules

Files

To open a file in python we will use open function and it will return a file object(For now just assume that file object is the python way of understanding files. We will see about it later in Class). There are a few important ways in which you can open a file with python. They are:
  • r - Read
  • w - Write
  • a - append
  • r+ - read and write
In Read mode we open the file with just the permission to read the data in the files. We cannot make any changes to the file.
In the Write mode we can only write the data to the file. It should be noted that if there is an existing file in the directory, then the whole data in the file is erased and made ready for the new data.
In the append mode, the file is opened to write data at the end of the file. i.e. the new data is just appended to the file.
In the Read and Write mode, we are opening the file with both reading and writing permissions.
NOTE: open function by default assumes r mode. i.e. r is the default argument value of the open function.
For the example we will start writing operation and then reading the contents of the same file.
In [68]:
# open a file
# remember to enclose the filename and mode in quotes
f = open('roc.txt', 'w')
# writing a sentence to the file
f.write('This is a test file')
Now open the folder and you will see a file with name roc.txt with the contents This is a test file.
As our work is completed, we will go ahead and close the file. It is an important operation.
In [69]:
# close the file after use
f.close()
In [70]:
# open the file in read mode
f = open('roc.txt', 'r') # mentioning 'r' is optional
# this will read the contents of the whole file
print f.read()
# close the file after use
f.close()
This is a test file
The appending operation.
In [71]:
# open the file
f = open('roc.txt', 'a')

# appending
f.write('This is the appending operation')

# close the file
f.close()
In [72]:
# lets check the contents of the file
f = open('roc.txt')

# printing the whole file
print f.read()

# close the file
f.close()
This is a test fileThis is the appending operation
As you have seen, it is disgusting to close the file after using it. But if you don't close the file there will be lot of problems. Sometimes you may forget to close the file. For this you can use with operator. Lets see an example.
In [73]:
# opening file using 'with'
with open('roc.txt') as f:
    print f.read()

# check if the file is close
print f.closed # True if close else False
This is a test fileThis is the appending operation
True
You can read more about files from Input and Output

Errors and Exceptions

In programming there are three main classifications of errors. To be simple:
  • Syntactic Errors
  • Exceptions
  • Logic Errors
In the first kind of errors, computer was not able to understand your code. Examples include forgetting :, using true instead of True etc.. These errors will not even allow the program to run.
In the second kind of errors, the program is syntactically correct, but the computer raises an exception when the program is running. Some examples include ZeroDivisionError, NameError etc.
In the third kind of errors which are the most trickiest of the errors, computer will not find any errors in your syntax not while execution but the output you are expecting will not be shown. Actually there is an error in your algorithm or implementation of the algorithm.
Lets see an example of an error.
In [74]:
if True print 'Hello world'
  File "<ipython-input-74-6bf26ff780a2>", line 1
    if True print 'Hello world'
                ^
SyntaxError: invalid syntax
As you can see, this error is a syntax error and is of the first type of error. Now we will have a look at the second type of errors also called as exceptions.
In [75]:
# ZeroDivisionError
print 10 * (1/0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-75-339e4a3a67c3> in <module>()
      1 # ZeroDivisionError
----> 2 print 10 * (1/0)

ZeroDivisionError: integer division or modulo by zero
In [76]:
# Using a variable without creating it
print Anivarth
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-76-95d0e9ac3c90> in <module>()
      1 # Using a variable without creating it
----> 2 print Anivarth

NameError: name 'Anivarth' is not defined
In [77]:
# concatenating string and a number
print '2' + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-77-b9121cd4659d> in <module>()
      1 # concatenating string and a number
----> 2 print '2' + 2

TypeError: cannot concatenate 'str' and 'int' objects

How to handle exceptions

Sometimes you are aware of that exceptions are gonna occur and you want python to ignore then and continue with the program execution. You can handle exceptions with python try and except code.
Lets see an example
In [78]:
try:
    zero_error = 1/0
except:
    print "I have suppressed an error and continued the execution of program"
I have suppressed an error and continued the execution of program
You can also suppress some specific exceptions in your code. You can do that as follows:
In [79]:
try:
    zero_error = 1/0
except ZeroDivisionError:
    print "It was a Zero Division Error"
except ValueError as e:
    # e is the error that python is telling
    print "Value error and the error reaised by python is "+str(e)
It was a Zero Division Error
You can read more about errors and exceptions from Errors and Exceptions - Python docs

Classes

According to me, I cannot cover all the information regarding the classes here. After reading this introductory part you should go to the documentation and read the whole article about classes. Here I will only introduce you to what classes are, methods etc. But remember again classes is a very important topic and you should read more about classes from other sources also.
Python is also one of the object oriented programming language. Actually according to me, classes are a simple and easy way to group together all the code that has some relation. For example if I give you the following list and to group together all the items that belong to one class,
  • car
  • dog
  • cat
  • lion
  • truck
  • airbus A380
  • boeing 737
  • train
    then the grouping may be approximate as follows:
Road Vehicles
  • car
  • truck
  • train
Aircrafts
  • airbus a380
  • boeing 737
Animals
  • dog
  • cat
  • lion
Lets make some functions for each of the members in our list.
In [80]:
# definition for car
def car():
    print "I travel on road"
    print "I abide traffic rules"

# dog
def dog():
    print "I am an animal"
    print "I bark"

#car
def cat():
    print "I am an animal"
    print "I meow"

#lion
def lion():
    print "I am an animal"
    print "I roar"

#truck
def truck():
    print "I travel on road"
    print "I am bigger than car"

#airbus a380
def airbus_a380():
    print "I fly"
    print "I am A380"

# boeing 737
def boeing_737():
    print "I fly"
    print "I am B737"

# train
def train():
    print "I travel on road"
    print "I am bigger than truck"
Now as you can see, each of these functions have a lot in common. Eventhough the code can be made simple, the problem of complexity remains the same. To solve this problem we will create classes.
In the code above, each object is printing the first statement that is common to its class but also printing its own personal opinion. So when defining the class we will ask the object to just give its opinion and we will add that to the common print statement that its class has. Lets see the code
In [81]:
class RoadVehicles:
    def __init__(self, personal_statement):
        self.personal_statement = personal_statement
    def vocalize(self):
        print "I travel on road"
        print self.personal_statement

class Aircrafts:
    def __init__(self, personal_statement):
        self.personal_statement = personal_statement
    def vocalize(self):
        print "I fly"
        print self.personal_statement

class Animals:
    def __init__(self, personal_statement):
        self.personal_statement = personal_statement
    def vocalize(self):
        print "I am an animal"
        print self.personal_statement
We define a class with class followed by its name. If we want to class to take any input we will put then in the __init__ function(Again this a broader perspective. You should read a lot to understand more and better). Every function will take self as the first argument. I will explain you what self is. When you will be using this classes say RoadVehicles to define an object car, then the self means that the value belongs to the car. To put it in a simple way, when you want the car to print its personal option alone you will ask car.personal_statement, then it asks python self.personal_statement(or tell me my personal statement). I hope you have got a broader picture of the same.
Lets use our classes to create some objects.
In [82]:
a380 = Aircrafts("I am A380")
print a380.personal_statement # I am A380
a380.vocalize() # I fly & I am A380
I am A380
I fly
I am A380
You can see the exact output that we wished, but the code is lot neat and also easily understandable eliminating a lot of duplication.
You can and should read more about Classes from the following:
I hope by the end of this doc, I have given you a broader understanding of what python is all about. I know that this one will be a very good introduction for people who have already programmed before and a little bit of struggle for people who are new to programming. For the later people I would suggest you to read each and every link that I have pointed out here, so that you will not miss a point leaning python. Last but not the least, to get a stronger and better understanding of python you should read Python Docs. Further more if you have any doubt then just google it and probably a similar answer had already been asked on Stack Overflow. To improve your knowledge of python you can type in your area of interest and find a lot of resources.
Have fun pythoning :)
As always if you have any doubts or didn't understand anything, comment in the comment box below and I will be glad to help you.
If you have any suggestions or want me to add any new topic to this chapter then please do comment in the comment box below and I will be happy to see the comment.
If I have made any typo or grammatical error, comment in the comment box and I will rectify the problem as soon as possible.
You can also contact me.
Thank you. Have a nice day😃.

Popular posts from this blog

Problem 60 Project Euler Solution with python

Prime pair sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. This problem is j u st a brute force problem. If you have come here because you don't know the limit upto which you will h ave to gener ate the prime numbers t hen go ahe ad and t r y with 10,000 . When I first start ed solving the problem I chose 1 million(beca use most of the problem s on project E uler have this limit ), but it took very long for the computer to fin d the solution. After searching on the internet then I found many people choosing 10, 000 so I have changed my in put f rom 1 million to 10000 and the output was f ast. He...

Add/Embed SVG to Blogger website

In this post I will tell you my method(trick) of adding SVG images in a blogger website or blog. Before starting , the first thin g I am assu m ing is that you are aware of SVG if you are here. If not please see S calable V ec tor G raphics Recently when I tried to embed a SVG image for a post on pygal, I tried uploading the SVG file and blogger Image uploader came up with an error, because of which I had to find some other way.  SVG File upload Error in Blogger  I started sea rc hing Google " Embed SVG in Blogger " . I found blogorrhea , w h ich gave some i nformatio n on add ing SVG directly as a markup , which worked , but I faced another problem using this . Also th is guy has used lot of Javascript which was confusin g for me, being new to using SVG.   So I first t houg ht of learning on h ow to embed SVG in HTML and t his on e worked out. Actually we can embed SVG in HTML i n following ways: Using Object tag Using Iframe tag Using embed...

Making a quiz web app with python and flask

Edit : When you are creating a web app with h tml templates, then y ou will have to sa ve the html file in templates folder in the Current Wor ki ng Directory( CWD). If you save the file in the C W D directl y you will get a TemplateNotFound error. Thank you Udhay for pointing it out.   In this post we will create a quiz website using python . I will be using the flask framework . After reading this tutorial you will learn form submission , flask templates , python code in flask templates , shuffling the questions and options with the random module and few others.  Please note that this tutorial is not big as it seems to be. Some of the code has been rewritten to maintain consistency and also font size is somewhat big so that your eyes won't get stressed reading this tutorial. Also the content has not occupied the full width of the page. In this tutorial I am assuming that you are having a very basic understanding of the flask framework . Please refer the documenta...