Python – Basics

1. Overview

1.1. What is Python

Python is an interpreted programming language and claims to be a very effective programming language. Python was develop by Guido van Rossum.

The name Python is based on the TV show called Monty Python’s Flying Circus. During execution, the Python source code is translated into byte code which is then interpreted by the Python interpreter. Python source code can also run on the Java Virtual Machine.

Key features of Python are:

  • high-level data types, as for example extensible lists
  • statement grouping is done by indentation instead of brackets
  • variable or argument declaration is not necessary
  • supports for object-orientated, procedural and functional programming style

1.2. Block concept in Python via indentation

Python identify blocks of code by indentation. If you have an if statement and the next line is indented then it means that this indented block belongs to the if. The Python interpreter supports either spaces or tabs, e.g. you can not mix both. The most “pythonic” way is to use 4 spaces per indentation level.

2. Programming in Python


The following create a single line comment.

# This is a comment 

2.2. Variables

Python provides dynamic typing of its variables, e.g. you do not have to define a type of the variable Python will take care of this for you.

# This is a text
s= "Lars"
# This is an integer
x = 1

2.3. Assertions

Python provides assertions. These assertions are always called.


2.4. Methods / Functions in Python

Python allows to define methods via the keyword def. As the language is interpreted the methods need to be defined before using it.

def add(a,b):
    return a+b

print add(1,2)

2.5. Loops and if clauses

The following demonstrates a loop the usage of an if-clause.

i = 1
for i in range(1, 10):
    if i <= 5 :
        print 'Smaller or equal than 5.\n'
        print 'Larger than 5.\n'

2.6. String manipulation

Python allows the following String operations.

Table 1. 

Operations Description
len(s) Returns the length of string s
s[i] Gets the element on position i in String s, position start with zero
s[-i] Get the i-tes Sign of the string from behind the string, e.g. -1 returns the last element in the string
“abcdefg”[0:4] Gets the first 4 elements (abcd)
“abcdefg”[4:] Gets the elements after the first 4 elements (abcd)
`a`+`b` + `c` Concatenates the int varibles a, b,c, e.g. if a=1, b=2, c=3 then the result is 123.
s.lower() Result will be s in lower cases
s.upper() Result will be s in upper cases
s.startswith(t) True, if s startsWith t
s.rstrip() Removes the end of line sign from the string

For example:

s = "abcdefg"
assert (s[0:4]=="abcd")
assert (s[4:]=="efg")
assert ("abcdefg"[4:0]=="")
assert ("abcdefg"[0:2]=="ab")

2.7. Concatenate strings and numbers

Python does not allow to concatenate a string directly with a number. It requires you to turn the number first into a string with the str() function.

If you do not use str() you will get “TypeError: cannot concatenate ‘str’ and ‘int’ objects”.

For example:

print 'this is a text plus a number ' + str(10)

2.8. Lists

Python has good support for lists. See the following example how to create a list, how to access individual elements or sublists and how to add elements to a list.

Created on 25.11.2015

@author: Anukul Verma

This is the way to comment multiple lines
mylist = ["Linux", "Mac OS" , "Windows"]
# Print the first list element
# Print the last element
# Negativ values starts the list from the end
# Sublist - first and second element
# Add elements to the list
# Print the content of the list
for element in mylist:

If you want to remove the duplicates from a list you can use:

mylist = ["Linux", "Linux" , "Windows"]
# remove duplicates from the list
mylist = list(set(mylist))

2.9. Processing files in Python

The following example is contained in the project “de.vogella.python.files”.

The following reads a file, strips out the end of line sign and prints each line to the console.

Created on 25.11.2015

@author: Anukul Verma

f = open('c:\\temp\\myexample.txt', 'r')
print f
for line in f:
    print line.rstrip()

The following reads the same file but write the output to another file.

@author: Anukul Verma

f = open('c:\\temp\\myexample.txt', 'r')
output = open('c:\\temp\\new_file.txt', 'w')
for line in f:
    output.write(line.rstrip() + '\n')

2.10. Splitting strings and comparing lists.

The following example reads two files which contain one long comma separated string. This string is splitted into lists and the lists are compared.

f1 = open('c:\\temp\\launchconfig1.txt', 'r')
s= ""
for line in f1:

f2 = open('c:\\temp\\launchconfig2.txt', 'r')
s2= ""
for line in f2:
list1 = s.split(",")
list2 = s2.split(",");

difference = list(set(list1).difference(set(list2))) 

print (difference)

2.11. Writing Python Scripts in Unicode

If you read special non ASCII sign, e.g. ö, ä. ü or ß, you have to tell Python which character set to use. Include the following in the first or second line of your script.

# -*- coding: UTF-8 -*-

2.12. Classes in Python

The following is a defined class in Python. Python uses the naming convension __name__ for internal functions.

Python allows operator overloading, e.g. you can define what the operator + will to for a specific class.

Table 2. 

__init__ Constructor of the class
__str__ The method which is called if print is applied to this object
__add__ + Operator
__mul__ * Operator

The empty object (null) is called None in Python.

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return "x-value" + str(self.x) + " y-value" + str(self.y)
    def __add__(self,other):
        p = Point()
        p.x = self.x+other.x
        p.y = self.y+other.y
        return p
p1 = Point(3,4)
p2 = Point(2,3)
print p1
print p1.y
print (p1+p2)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s