Mark & Click - Python Interactive Tutorial
  • Beginner
  • Advance
  • Blog

Interactive Python Tutorial



This tutorial is intended primarily for python beginners (more complex and popular problems are covered here), in-order to become a python developer, you should solve all the exercises followed by every subject in the following contents list. Each such exercise contains most of the code, your goal is to complete the lines in the exercise. You should activate the "run" button and check your results.

Be aware, "run" button executes your code just as a regular python interpreter, any "imports" of external libraries is forbidden.  

Additionally, you may find the following sites also useful
for learning python interactively.
http://www.trypython.org/, 
http://www.learnpython.org/ .


As opposed to other available tutorials over the web (e.g. i have mentioned above), this tutorial  will cover interesting tips and tricks illustrated through exercises and examples, additional more complex and popular problems for advanced python users are presented here.

Contents:

  • Hello World!.
  • Numbers.
  • Strings.
  • Data Structures
    • List.
    • Set.
    • Dictionary.
  • For,While Loops, List comprehension, map.
  • Functions.
  • Classes , Polymorphism.


Hello World!

I will demonstrate a way to print 'Hello World'.
>>print 'Hello World'
Hello World

Exercise 1:

Complete the print line, so that it will print 'Bye User'
print ' '





Numbers

I will demonstrate a way to print addition, subtraction, multiplication and division of two numbers. Result = 1
>>print 2*6/3/4
1

Exercise 2:

Complete the print line, so that it will print 4
print 4* /3





Strings

I will demonstrated how to concatenate strings
>>print 'Hello ' + 'Hello'
Hello Hello
>>x = 'Hello '
>>print x + x 
Hello Hello 
>>print x * 2
Hello Hello

Exercise 3:

Complete the statements so that the output will be "Hello User! Bye, Bye, Bye,"
x = 'Bye, '
y = ''

print 'Hello' + y + (x * )





Data Structures (list,set,dictionary).

List:

List: Demonstration of how to use a list
>>l = [3,"Hello",[4,5,4]]       #create a list   
>>print l
[3, 'Hello', [4, 5, 4]]

>> print l.index("Hello")       #find out the index of a specific element
1
>> print l.index([4,5,4])
2

>> print (3 in l)               #check existence
True
>> print "H" in l
False
>> 

>> l.insert(2,"H")              #insert item into the list
>> print l
[3, 'Hello', 'H', [4, 5, 4]]
>> print "H" in l
True
>> len(l)                       #length of a collection
4

Exercise 4:

Complete the statements so that the output will be "Bye User!!!"
#define first list
x = ['Hello','User','Bye']
#define second list
y = []

y.insert(0,x[2])
y.insert(              # insert item from the fist list to the second

y[1] = y[1] + ' '             # Change the second item of the new list

print y[0]+ ' ' + y[1]        # should print 'Bye User!!!'






Set:

Set: Demonstration of how to use a set
>> s = set([3,"Hello","H"])     #create a set 
>> print s
set(['H', 3, 'Hello'])

>> s.add('L')                   #add item to a set 
>> print s
set(['H', 3, 'Hello', 'L'])

>> s2 = set(['H', 3, 'Hello', 'M'])
>> print s2
set(['H', 3, 'M', 'Hello'])


>> print s2.intersection(s)      #intersection 
set(['H', 3, 'Hello'])
>> print s2 & s                  #intersection
set(['H', 3, 'Hello'])
>> print s2.union(s)
set([3, 'H', 'M', 'L', 'Hello']) #union
>> print s2 | s
set([3, 'H', 'M', 'L', 'Hello'])
>> print s2.difference(s)        #difference
set(['M'])

>> len(s)
4

Exercise 5:

Complete the statements so that it will print the last item in s2 that do not exists in s1 "4"
#define two sets
s1 = set([1,3,5,6])
s2 = set([1,2,4,5,6])

res = list(s1)           # create a list from a set
lastItemInList = res[-1] # extract the last item from list


print list(s2.  )[]      # print the last item in s2 that do not exists in s1 (4)




Dictionary (Hash Table):

Dictionary: Demonstration of how to use a dict

>> d = dict([('id1','red'),('id2','green')])
>> print d
{'id2': 'green', 'id1': 'red'}
                  
>> d[3] = 'yellow'                                # add item to a dict
>> d[4] = 4
>> d[10] = [1,2,3]
>> print d
{4: 4, 10: [1, 2, 3], 3: 'yellow', 'id2': 'green', 'id1': 'red'}

>> print d.keys()                                 # dictionary keys
[4, 10, 3, 'id2', 'id1']
>> print d.values()                               # dictionary values
[4, [1, 2, 3], 'yellow', 'green', 'red']

>> d[10].append(4)                                # change the value object
>> print d[10]
[1, 2, 3, 4]

>> print 10 in d.keys()
True

Exercise 6:

Complete the statements so that the output will be all the unique values of dictionary 1 ( set(['color1', 'color3', 'color2']) )
#define two dictionaries
d1 = dict([('key1','color1'),('key2','color2'),('key3','color3'),('key4','color1')])
d2 = {}                # also a definition for dictionary

d2['key5'] = list(d1. )  # append all values from d1 to the value of a key4 for d2

print set(d2  )       # print all unique values for d1





For,While Loops, List comprehension, map.

Demonstration, of how to use loops and list comprehension.

>> d1 = dict([('key1','color1'),('key2','color2'),('key3','color3'),('key4','color1')])

>> d2 = set()

>> for key in d1.keys():     # iterate over the dictionary keys
    d2.add(d1[key])          # add each value to a set

>> print d2
set(['color1', 'color3', 'color2'])
>> d3 = set(d1[key] for key in d1.keys()) #do the same as before
>> print d3
set(['color1', 'color3', 'color2'])

>> print list([i for i in range(0,12,2)]) # iterate over number 0-10 with step=2
[0, 2, 4, 6, 8, 10]

>> i = -1
>> l = list()
>> while (i < 10):
     i+=1
     if (i % 2):                # test for modulo 
        continue;               # continue with while loop
     l.append(i)

>> print l
[0, 2, 4, 6, 8, 10]

>> l = map(lambda x: x if not x % 2 else x+1, range(0,10)) """ iterate over 
a list of numbers 0->10, every number that has modulo (not even) 
and transfer it to the same number + 1"""
>> print l
[0, 2, 2, 4, 4, 6, 6, 8, 8, 10]
>> print list(set(l))
[0, 2, 4, 6, 8, 10]

Exercise 7:

Print all the number between 0 and 100 that are devidable by 3 and 5 ([0, 15, 30, 45, 60, 75, 90])
l = range( , )

print [i for i in l if (( ) and (not i%5))]



Exercise 8:

Multiply each number from a list of 0-100 numbers, by 2. Print only the first 10 number that are devidable by 3
l =  map(lambda x: (x *  ),range(100))    #should multiple each item by '2'

filteredList = [i for i in l if (not i% )] #return only numbers with i%3 = 0

i=0
l = []
for elem in filteredList:
    if i >=  :                # only the first 10 numbers should be printed
        break
    i+=                       # advance i for every iteration
    l.append( )               # append the filtered elem into l
    
print l





Functions

Demonstration, of how to define and use function.

#definitions of 3 functions
>> def addNumbers(x,y):
    return x+y

>> def multiply(x,y):
    return x*y

>> def power(base,po):
    return base ** po             # '**' is a power operator


>> l = [addNumbers,multiply]      #list of functions


>> print [power(i,2) for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>> print map(lambda x: multiply(x,3),range(10))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
>> print map(lambda x: l[0](x,3),range(10))   #execute function addNumbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

>> print [l[i%2](i,3) for i in range(10)]     """ addNumbers will be called for
 odd numbers, multiply for even """
[3, 3, 5, 9, 7, 15, 9, 21, 11, 27]

Exercise 9:

print the first 10 even numbers ([0, 2, 4, 6, 8, 10, 12, 14, 16, 18] )
#define functions
def isOdd(x):
    return x %                #odd -> modulo x % 2 > 0 -> True 

def isEven(x): 
    return not x%             #even -> the opposite of odd

def filterBigList(bigLi, n):
    return [bigLi[ ] for i in range(n)]   # return only the first n items 

l =  [i for i in range(100) if isEven(i)] # collect or even numbers

print filterBigList(l,10)                 # print the first 10 items  





Classes , Polymorphism

Demonstration, of how to define classes and use object instances

#abstract Animal class (part of the methods have to be implemented

>> class abstractAnimal(object):            
    def __init__(self,wild=False):    # constructor with default argument
        self.wild = wild
    
    def bark(self):                   # abstract method
        raise NotImplementedError( "Should have implemented this" )
    
    def walk(self,steps):              # implemented method, could be overridden
        print "Walking %s steps" % steps

    def isWild(self):                  # getter
        return self.wild
        
>> class wolf(abstractAnimal):        # inherits from abstract Animal class
    def bark(self):                   # implements the abstract method
        print "hooooowll"

>> class dog(abstractAnimal): 
    def bark(self):
        print "woof"



""" calls the default constructor of dog, that calls the constructor of abstract animal first"""

>> my_dog = dog()                   
>> my_wolf = wolf(wild=True)

>> my_dog.bark()
woof
>> my_dog.walk(2)
Walking 2 steps

>> my_wolf.bark()
hooooowll
>> my_wolf.walk(2)
Walking 2 steps
>> print isinstance(my_dog,dog)
True
>> print isinstance(my_dog,abstractAnimal)
True
>> print isinstance(my_dog,wolf)
False

>> print my_wolf.isWild()
True
>> print my_dog.isWild()
False

Exercise 10:

print
class abstractHuman(object):            
    
    def __init__(self,id_human):    # constructor with default argument
        self.id_human = id_human
        
    def getId(self):
        return self.id_human
    
    def isHappy(self):
        raise NotImplementedError( "Should have implemented this" )
    
    def isStudent(self):
        return True

  
class student(abstractHuman):        # inherits from abstract Human class

    average = 0                      # no init -> the default human constructor will be called 
        
    def setAverage(self,average):
        self.average = average
    
    def getAverage(self):
        return self.average
    
    def isHappy(self):
        return self.average >= 80


class teacher(abstractHuman):        # inherits from abstract Human class
    def __init__(self,id_human,salary):
        self.salary = salary
        super(teacher,self).__init__(id_human)  # calling a super constructor for human
        
    def getSalary(self):
        return self.salary
    
    def isHappy(self):
        return self.salary >= 1000
    
    def isStudent(self):             # no need to implement it for a student
        return False
    
class university():
    
    def __init__(self):
        self.humansNum = []
        
    def getNumOfHumans(self):
        return len(self.humansNum)
  
    def getHumans(self):
        return self.humansNum
    
    def getNumberOfHappyHumans(self):
        return sum([1 if human.isHappy() else 0 
                    for human in self.humansNum ])
        
    def addHuman(self,human):
        self.humansNum.append(human)
        
    def getNumOfExcellentStudents(self):
        return sum([1 if (human.isHappy() and human.isStudent()) 
                    else 0 for human in self.humansNum ])
    
    def getNumOfExcellentTeachers(self):
        return sum([1 if (human.isHappy() and (not human.isStudent())) 
                    else 0 for human in self.humansNum ])
    


uni = university()

[uni.addHuman(teacher(i,1001)) for i in range(5)]
[uni.addHuman(teacher(i,999)) for i in range(5,10)]
[uni.addHuman(student(i)) for i in range(10,15)]

excellentStudent = student(15)
excellentStudent.setAverage(100)
uni.addHuman(excellentStudent)

print "Number of Humans %d" % uni.getNumOfHumans()
print "All IDs"
print [h.getId()  for h in uni.getHumans()]

print "Happy Human's IDs"
print [h.getId()  for h in uni.getHumans() if h.isHappy()]

print "Number of excellent students %d" % uni.getNumOfExcellentStudents()
print "Number of excellent teachers %d" % uni.getNumOfExcellentTeachers()





Copyright © 2011-2012

Michael Gorelik