I found my notes from the time when I was learning python. They are not quite tidy but might be useful. So I created this small python tutorial for newbies.

Python is a hybrid language which is interpreted by interpreter in the shell (or cmd). it has its own shell. You can easily switch to python shell from terminal by just writing “python”.

Python is a scripting language just like bash. It is high level and functional. This makes it readable. Nearly every job has a function in python. You can handle so many things in one line.
Python scripts can be run from python shell and they can be also run from python modules which are files with "py" extension. Every line in the module is interpreted and run by python shell and if there is an error, the operation stops. If the error is in a condition which is not reachable during that runtime, this error won't be seen by python shell. That's an interesting feature of python.
  • Open a new file. Name it. For ex: hello and Change its extension to "py". For my ex: hello.py
  • On linux you need to change its permission level. because it is a runnable script. So we need to give it execute permissions.
    • chmod +wx hello.py
  • Run it like a normal executable file:
    • ./hello.py
  • Recommended way:
    • python hello.py
Syntax is based on indentation. That's nice because it is forcing programmer to indent their lines carefully and of course helping readability.
There is no ";" to indicate line endings. newline is enough. There is also no brackets "{", "}". Again this is helping readability.
For strings both " " and ' ' could be used.
The variables has no types in python. In fact they have but while defining there is no variable type definition in front of them. The type is revealed on runtime.

Some action

#!/usr/bin/env python
# encoding: utf-8
"""
untitled.py

Created by Hakan Uysal on 2012-01-29.
Copyright (c) 2012 __MyCompanyName__. All rights reserved.
"""

def main():
    print ('i love hakanu.net')

if __name__ == '__main__':
    main()
  • #!/usr/bin/env python
    • This means that this is a python script and it must be run by python shell
  • # encoding: utf-8
    • This is for character encoding. Not mandatory
  • """
    • This is multiline comment start/stop indicator. It must match with same char.
    • For one line comments you need to use "#" char
  • def main():
    • As you know, main func where everyting starts.
  • print ('i love hakanu.net')
    • This is printing the line onto screen function. it is so flexible. You can write whatever you want by using "print"
  • if __name__ == '__main__':
  • This is for providing reusability by other modules. Sure i have my main func. That means im gonna use other functions. But somebody(some other module) may want to use my main. Not so big deal. It will be understood after experiencing more.

Write your own function:

def func1():
    a = 5
    print ('im func1 and im calling func2 with parameter : ' + str(a))
  • def func1():
    • define the name of function. Not use a function name such as mine. It is bad example.
  •     a = 5
    • Don't forget to indent the line. Define a variable. We are assigning it to an integer. This means that a will be an integer
  • print ('im func1 and im calling func2 with parameter : ' + str(a))
    • str(a) converts a from integer to string.

How to system functions and how to get command line arguments?

import sys
  • put this at the top your module. it is like "import" from java or "#include" from C/C++ or "using" from C# etc
  • Command line arguments are like the other languages:
    • sys.argv[0] --> name of the program
    • sys.argv[1] --> 1st command line argument
    • sys.argv[2] --> 2nd command line argument
    • ...
if len(sys.argv) == 2:
if sys.argv[1] == 'deli':
greeting = "Welcome" + sys.argv[1]
  • len measures the length of arrays. it is so generic just like the other functions. If the command line arguments more than 2, run this condition
  • We can see the basic usage of "if" conditions

Strings

#Immutable objects. You can not change its elements.

sName = 'hakanu.net'
#some cool functions
len(sName)  #length of string

print(sName[0])  #d
print(sName[1])  #e
print(sName[-1])  #m
print(sName[-2])  #o

print(sName[0:3])  #len
print(sName[0:-1])  #hakanu.net
find('dev')              #0
sName.replace('devdala', 'hakanu') #sName will be 'hakanu.com'
#printing with parameters
 print '%s got: %s expected: %s' % (sName, "five", "three")
sSentence = 'this is a sentence'      #define a string with whitespaces
lWords = []    #define a list to keep the words in the sentence
lWords = sSentence.split()

Loops

 list1 = [1,2,3]
 list2 = ['deli', 'coban', 'devdala']
 i = 0
 while i < len(list1):
 print 'Yo ' + list2[i]
 i = i + 1

 for aName in list2:
 print 'Yo ' + aName
#Look at the list definition list1 = [1,2,3] and list2 = ['deli', 'coban', 'devdala']

Lists and List of lists

#Enumarate lists
bigList = [['deli', 1], ['Peter', 2], ['coban', 3]]
for elem in bigList:
print elem
print 'Yo %s is %s years old' % (elem[0], elem[1])
 
#cooler
for i, name in enumerate(bigList):
print i, name
#list operations
        empty_list = []
 teammates = []
 #appending a single new item to the list
 teammates.append('deli')
 teammates.append('coban')
 teammates.insert(0, 'hakan')
 print "Before appending: " , teammates

 #appending another list to the list
 other_team = ['ali', 'veli', 'kirkdokuz', 'elli']
 for other_person in other_team:
 teammates.append(other_person)
 print "After appending: " , teammates

 #removing from list - only works with name
 teammates.remove('elli')
 #removing from list - by id
 teammates.pop(0)
 print 'After removing: ' , teammates

 #lists like strings
 print 'first 3 of list : ', teammates[0:3] 

Tuples

#the most asthounishing feature for myself
#tuples can not be modified in place like strings
#tuples are good for small elements which are diffrent

t = ('John', 'Peter', 'Susan')
print len(t)
#t.append('coban') #AttributeError: 'tuple' object has no attribute 'append'

l = [('peter', 28), ('coban', 31), ('deli', 30)]     #dont mess with elements - all of them needs to be in similar shape
for name, age in l:
print 'Printing tuple : ' , name , age

Sorting

 teammates = ['ali', 'veli', 'kirkdokuz', 'elli']
 print 'Teammates before sorting : ' , teammates
 teammates.sort() #modified the list in place -- IMPORTANT
 sorted_teammates = sorted(teammates) #sorted is another function provided by python
 print 'Sorted teammates : ' , sorted_teammates

 #tuple has no sort but sorted can be used
 t = ('John', 'Peter', 'Susan') 
 tuple(sorted(t))
 print 'Sorted tuple : ' , t

Yes everyting is reference like Java

 #everything is reference
 a = [1,2,3]
 b = a
 print a
 print b
 a.append(4)
 print b #it will be [1,2,3,4] a and b are pointing to same explicit copy

 c = list(a)
 a.append(5)
 print a #[1,2,3,4,5]
 print b #same as a [1,2,3,4,5]
 print c #[1,2,3,4]

Cool sorting, Sort by specified attribute

def SortBySpecifiedAttribute():
 l = ['Yellow', 'Blue', 'Red', 'Green'] #l is a list
 print 'l unsorted : ', l
 sorted(l)
 print 'l sorted alphabetically : ', sorted(l)
 #sort by length of the word
 #len('Blue') = 4, len('Green') = 5, len('Red') = 3, len('Yellow') + 6
 l.sort(key=len) #key is the key of sorting
 print 'l is sorted by element length : ' , l

 l = ['Yellow', 'blue', 'rED', 'Green'] #l is a list
 #sort by upper/lowercase
 #lower it func to make the string's elements lowercase str.lower()
 #lower is not like len. lower needs a string object. So we need a global func to give a key
 #Normally capitals comes first
 l.sort(key=MyLower) 
 print 'l is sorted by lowercase : ', l

def MyLower(str):
 return str.lower()

Dictionaries, cooler than tuples

def DictionariesInPython():
 ages = {} #keys have to be unique
 ages['John'] = 30
 ages['Peter'] = 27
 ages['Susan'] = 28

 print ages
 print ages['Susan']

 if 'Joe' in ages:
 print 'Print joes age' , ages['Joe']
 else:
 print 'No ages!'

 print 'Printing keys : ' , ages.keys()
 ages['Susan'] = 26

 keys = ages.keys()
 keys.sort() 

 for name in keys:
 print name, ages[name]

 print 'printing values: ', ages.values()

 for name, age in ages.items():
 print name, age

 print 'Printing age items as tuples: ' , ages.items()

 all_ages = ages.values()
 print 'Mathops on ages(average age) : ' , sum(all_ages) / len(all_ages)

 print 'More precision : ' , sum(all_ages) / float(len(all_ages))

 print ages

 l = [('peter', 28), ('coban', 31), ('deli', 30)]
 print 'before deletion l :' , l
 del l[0]
 print 'after deletion l : ' , l 

 mk = {}
 if 'John' in mk:
 mk['John'] += 1
 else:
 mk['John'] = 1
 print 'John check : ' , mk

 print 'print mk items as tuples : ' , mk.items()

 #RuntimeError: dictionary changed size during iteration
 #for name in mk:
 for name in mk.keys():
 if mk[name]<= 1:
 del mk[name]

 print 'printing mk after deletion : l ', mk

Reading text file

def ReadTextFile():
 f = open('filePy.txt', 'r') #open for reading - opening does not load the file into memory
 print 'File content: ' , f.read()
 print 'Read again the file content: ' , f.read() #the reader pointer is at the end of the file
 f.close()
 f = open('filePy.txt', 'r')
 print 'Read file appropriately : ' , f.readlines()
 f.close()

 f = open('filePy.txt', 'r')
 contents = f.read()
 print 'Show the # of ' , contents.count('salt')
 print 'Show the # of ' , contents.count('line')