Manipulation the Dictionary

d={10: 'iprg' , 22: 'Nan', 33:'Kool',8: 'Jool','y': 89,'tt':'toy',7:90 }
for i in d:                                
  print i,d[i]    # printing all the values in Dictionary          
print '\n'
print d[8]  #printing values of the individual keys
print '\n'
print d['y']  #printing values of the individual keys
print '\n'
print d[7]  #printing values of the individual keys
print '\n'
d[33]='hello world'  #updating the key 33 with new value
d[22]='pythonforengineers'   #updating the key 22 with new value
for i in d:                                
  print i,d[i]    # printing all the updated values in Dictionary    
del d[10]     # deleting key:value pair using key value -> 10
print'\n Dictionary after deleting a value:\n', d
d.clear()   #clearing all values
print '\n Dictionary after clearing all values:', d
del d   # Removing the Dictionary
try:
  print d
except:
  print 'Some error has occurred'
 

Creating a dictionary and traversing

d={10: 'iprg' , 22: 'Nan', 33:'Kool',8: 'Jool' } # Creating a dictionary with key: value pair

for i in d:                                     # Here key and the vaule can be any type.
  print i,d[i]                                  # Accessing elements in the dictionary

# Order in which they display is also different in output

print d.keys()  # print all keys in a dictionary

print d.values()  # print all values in a dictionary


Tuples Manipulation

try:
      l=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
      print 'List :',l
      tup1 = tuple(l) #Converts a list into tuple
      tup2=(1,2,3,4,5,6,7)
      #Adding two Tuples
      tup=tup1+tup2
      print 'New added tuple :',tup
      ntup=tup2*2
      print 'New multiplyed tuple:',ntup
      p=max(tup1)
      print 'The tuple with max value:',p
      p1=min(tup1)
      print 'The tuple with min value:',p1
      #Compares elements of both tuples and same return 0 otherwise -1
      k=cmp(tup2,ntup)
      print k
      #Delete Tuple
      del tup
      print tup
except:
      print 'Tuple does not exist'

Creation and accessing values in Tuples

t=(22,33,44,55,66,77,88,99) #A tuple is a sequence of immutable Python
print 'Tuple elements : ',t
#Accessing Values in Tuples
print 'Tuple first element :',t[0]
print 'tuple last element :',t[len(t)-1]
print '\n'
for i in t:
      print 'Elements in tuple: ',i
print '\n'
for i in range(len(t)):
      print 'Index :',i,'Vaule:',t[i]
   






Different indexing in string

fruit='apples'
l=len(fruit)
print 'Length of string:',l
print  fruit[0:4]    #[m:n]  m is starting index and n will upto n-1 index
print  fruit[-4]      # Index starting from last element as -1, second last element as -2 so on
print  fruit[::-1]   # Reverse of a string
print fruit[:2]
print fruit[2:]

try:
      print  fruit[6]
except:
      print 'index error'

for i in fruit:
      print '\nChar in the string: ',i

for j in range(l):
      print  '\nIndex and Char in the string: ',j,fruit[j]


Compare the two string based on ascii values

str1=raw_input('Enter the string 1:  ')
str2=raw_input('Enter the string 2:  ')
if str1==str2:
      print 'String are equal'  # It is working based on ascii value  refer http://www.ascii-code.com/
elif str1<str2:
      print 'Str2 is greater than str1'
elif str1>str2:
        print 'Str1 is greater than str2'
elif str1<=str2:
        print 'Str1 is greater than or equal to str2'
elif str1>=str2:
        print 'Str1 is greater than or equal to str2'
elif str1!=str2:
        print 'Str1 is not equal to str2'

Converting a for loop to corresponding while loop

for count in range(0,100,2):
   print 'For:',count

count1 =0
while(count1<100):
  print 'While:',count1
  count1=count1+2

Evaluating expression in Python

x=2
y=3
z=2

print x**y**z  #Answer 512

print (x**y)**z  #Answer 64

print x**(y**z)  #Answer 512


Perimeter and area of a circle and finding Natural Exponential Function

import math
r=int(raw_input('Enter the radius of circle:'))
perimeter=2*math.pi*r
print 'Perimeter of a circle :',perimeter
area=math.pi*(r**2)
print 'Area of acircle :',area

x=int(raw_input('Enter the value of x in y=e**x:'))
y=math.e**x
print 'Natural Exponential Function value :',y

Sorting the numbers in the List

L=int(raw_input("Enter the length of list: "))
p=list()
for i in range(L):
      num=int(raw_input("Enter the elements : "))
      p.append(num)
print '\nUnsorted list is: ',p
for i in range (len(p)):
 for j in range (i+1,len(p)):
  if p[i]>p[j]:
   t=p[i]
   p[i]=p[j]
   p[j]=t
else:
 print '\nSorted List is:' ,p

Search the Element in a list

flag=0
L=int(raw_input("Enter the length of list: "))
p=list()
for i in range(L):
      num=int(raw_input("Enter the elements : "))
      p.append(num)
j=int(raw_input("Enter the element to find: "))
     
for i in range(L):
      if (p[i]==j):
            flag=1
if flag==1:
      print "Element is found"
else:
        print "Element is not found"

Delete Duplicate numbers in a list

l1=list()
l2=list()
w=int(raw_input("Enter the elements in list:"))
for i in range(w):
      n=int(raw_input("Enter the list:"))
      l1.append(n)

for i in l1:
 if i not in l2:
  l2.append(i)
print ' Delete Duplicate numbers in a list: ', l2

Program to check the Perfect Number or Not

num=input("Enter the number:")
i=1
while i<=num/2:
 s=i**2
 if s==num:
  print "perfect square"
  break
 i+=1
else:
 print "Not a perfect square"

Program to find even number using functions without return

def even(n):
      if  n%2==0:
            print 'Even number'
      else:
            print 'Odd Number'

n=int(raw_input('Enter the number to check even or not:'))
even(n)  # No return from function but the message is displayed inside the function itself

Simple Calculator using functions

def su(a,b):  
      c=a+b
      print 'Added value is:',c
     
def subt(a,b):
            if a>b:
                  c=a-b
                  print 'Subtracted value is:',c
            else:
                  c=b-a
                  print 'Subtracted value is:',c
                  
def mul(a,b):
      c=a*b
      print 'Multiplication value is:',c

def div(a,b):
      if b==0:         
            print 'Division by zero not defined'
      else:
            c=float(a)/b
            print 'Divison value is:',c

def exp(a,b):
      c=a**b
      print 'Exponent value is:',c


a=int(raw_input('Enter the value of a:'))
b=int(raw_input('Enter the value of b:'))
print ' 1. add  2.sub  3.mul  4. div  5.exp'
n=int(raw_input('Enter the choice:'))
if n==1:
      su(a,b)        # Function call
elif n==2:
      subt(a,b)    # Function call
elif n==3:
      mul(a,b)          # Function call
elif n==4:
      div(a,b)    # Function call
elif n==5:
      exp(a,b)    # Function call
else:
      print 'Invalid options'

Sum of digits of the a given number

n=int(raw_input('Enter the number: '))
sum=0
while n>0:
      rem=n%10
      sum=sum+rem
      n=n/10
print 'Sum of digits of the number is: ',sum

Car Class Program

# define the Vehicle class
class Vehicle:
    name = ""              # initial value setting inisde the clas iteself
    kind = "car"           # initial value setting inisde the clas iteself
    color = ""             # initial value setting inisde the clas iteself
    value = 100.00         # initial value setting inisde the clas iteself
    def description(self): # creating function inside the class amd return as string
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str
     
     
car= Vehicle()             # creates a object [car1] for class vehicle
print car.description()    # using created object calling the function inside class


car1 = Vehicle()           # creates a object car for class vehicle
car1.name = "Fer"          # using object[car1] variables on the class vehicle is assigned
car1.color = "red"         # using object[car1] variables on the class vehicle is assigned
car1.kind = "convertible"  # using object[car1] variables on the class vehicle is assigned
car1.value = 60000.00      # using object[car1] variables on the class vehicle is assigned

car2 = Vehicle()
car2.name = "Jump"
car2.color = "blue"
car2.kind = "van"
car2.value = 10000.00

print car.description()    # Using object [car] created calling the functions[description()]inside the class
print car1.description()   # Using object [car1] created calling the functions[description()]inside the class
print car2.description()   # Using object [car2] created calling the functions[description()]inside the class

Simple Class Program in Python

class MyClass:          # class is created
    variable = "blah"   # variable is created and assigned the value

    def function(self): # funtion is created iniside the class as self
        print "This is a message inside the class."
       
       
       
myobjectx = MyClass()     # object[myobjectx] is created for class
myobjectx.variable        # using created object variable in the class is accessed

myobjecty = MyClass()          # object[myobjecty] is created for class
myobjecty.variable = "yackity" # using created object variable in the class new value is assigned

print myobjectx.variable       # using corresponding object and variable the value is displayed
print myobjecty.variable       # using corresponding object and variable the value is displayed
print MyClass.variable         # using corresponding object and variable the value is displayed

myobjectx.function()           # using corresponding object and function inside the class is accessed

A database with integer key using pickle

import anydbm
db = anydbm.open('integer.db', 'c')
import pickle
# A limitation of anydbm is that the keys and values have to be strings.
#  If you try to use any other type, you get an error

# The pickle module can help. It translates almost any type of object into a string suitable
# for storage in a database, and then translates strings back into objects.
k = 1
f=pickle.dumps(k)
db[f] = 'Babu'
print 'Value:',db[f]
print 'Key:',f
db.close()
r=pickle.loads(f)
print 'Key Value back:',r

Create database and store key value pairs

import anydbm
db = anydbm.open('captions.db', 'c')
db['c1'] = 'Photo of John Cleese.'
print db['c1']
db['c2'] = 'Photo of John Cleese doing a silly walk.'
print db['c2']

for key in db:
      print key

db.close()

Value Meaning
'r' Open existing database for reading only (default)
'w' Open existing database for reading and writing
'c' Open database for reading and writing, creating it if it doesn’t exist 
'n' Always create a new, empty database, open for reading and writing

anydbm in python.org package
dbm in anaconda package

To use try except for error handling

try:
      s=0
      g=s/0   # Division by zero creates error
      print 'Value of g :',g

except:
      print 'Something went wrong.'



try:
      s=0
      g=s/10   # Division by zero by 10  creates no error
      print 'Value of g :',g

except:
      print 'Something went wrong.'

Decimal Number to Binary number conversion

n=int(raw_input('Enter the Number'))
h=" "
while n>0:
  n1=n%2
  print 'R',n1
  n=n/2
  print 'V=',n
  h=h+str(n1)
print 'Binary Number is:',h[::-1]
 

Binary Number to Decimal Conversion

k=int(raw_input('Enter the binary number:'))
b=k
c=0
while b>0:
  b=b/10
  c=c+1
print c  
n=0
sum=0
while n<c:
  r=k%10
  k=k/10
  sum=sum + (r*(2**n))
  n=n+1
print 'Decimal Number is:', sum

Trigonometric Functions

import math
d=int(raw_input('Enter the angle in degree:'))
x= math.radians(d)
print 'Corresponding Radians is:',x           #Converts angle from degrees to radians.
f1=math.acos(x)                                                          # Return the arc cosine of x
print 'acos',f1
f2=math.asin(x)                                                           #Return the arc sine of x
print 'asin',f2
f3=math.atan(x)                                                          #Return the arc tangent of x
print 'atan',f3
f4=math.cos(x)                                                            #Return the cosine of x
print 'cos',f4
f5=math.sin(x)                                                             #Return the sine of x
print 'sin',f5
f6= math.tan(x)                                                            # Return the tangent of x
print 'tan',f6

u=int(raw_input('Enter the value of x:'))
v=int(raw_input('Enter the value of y:'))
e=math.hypot(u, v)                                                 #Return the Euclidean norm, sqrt(u*u + v*v)
print 'The Euclidean norm:',e

Accessing Values in Strings and Updating

var = 'Python Programming'
print "var[0]: ", var[0]
print "var[3:9]: ", var[3:9]
print "var[1:5]: ", var[1:5]
print "var[:]: ", var[:]           # List all elements in string
print "var[:2]: ", var[:2]       # List first 2 elements in string
print "var[2:]: ", var[2:]      # Except first 2 elements in string
print "var[::-1]: ", var[::-1]  # String Reverse
j=len(var)
print 'Length of string is:',j
i=0
while i<j:
      print 'Character in the string is:', var[i]
      i=i+1

x = 'Hello World!'

print "Updated String :- ", 'New ' + x[6:12]

Simple calculator using if elseif else and nested if else

a=int(raw_input('Enter the value of a:'))
b=int(raw_input('Enter the value of b:'))
print ' 1. add  2.sub  3.mul  4. div  5.exp'
n=int(raw_input('Enter the choice:'))
if n==1:
      c=a+b
      print 'Added value is:',c
elif n==2:
      if a>b:     #Nested if else
            c=a-b
            print 'Subtracted value is:',c
      else:
            c=b-a
            print 'Subtracted value is:',c
elif n==3:
      c=a*b
      print 'Multiplication value is:',c
elif n==4:
      if b==0:          #Nested if else
            print 'Division by zero not defined'
      else:
            c=float(a)/b
            print 'Divison value is:',c
elif n==5:
      c=a**b
      print 'Exponent value is:',c
else:
      print 'Invalid options'

Factorial using while loop

f=i=1
n=int(raw_input('Enter the number: '))
while i<=n:
      f=f*i
      i=i+1
print f

To check the number is Prime or Not

n=int(raw_input('Enter the number to check:'))
flag=0
i=2
while(i<=(n/2)):
    if (n%i==0):
        flag=1
    i=i+1
if(flag==0):
    print  'The number ',n, ' is prime number'
else:
    print 'The number ',n, ' is not prime number'

Factorial using Recursion



def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)


num = int(input("Enter a number: "))

if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of",num,"is",recur_factorial(num))

Searching the character count from string

word = raw_input('Enter the String:')
char = raw_input('Enter the Character to search:')

count = 0
for letter in word:
 if letter == char:
  count = count + 1
print 'Number of times repeated:', count

Basic String Manipulations

word = 'banana talks'

for i in word:  #Here the i is the letters in the string word
      print 'Character from string:',i

for h in range(len(word)):   #Here the h is index created by range function with value created by length
      print 'Index:',h,'charater:' ,word[h]

n1 = word.upper()

print 'String in the upper case:', n1

n2 = word.lower()

print 'String in the lower case:', n2

print 'Display a part of string :',word[1:5] # It display string from index 1 to 4

print 'Display a part of string :',word[4:8] # It display string from index 4 to 7

Factorial of a Number

# Python program to find the factorial of a number provided by the user.


num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

Lisiting particular type of files in a directory

import os
Path = os.getcwd()
Names= os.listdir(Path)
h=raw_input('Enter the file type extension: ')
for n in Names:
      if h in n:
            print n

Enter the sum of n numbers using file

n=int(raw_input('Enter the n for sum of n numbers: '))
f=open('integers.txt','w')
for count in range(n+1):
      f.write(str(count)+"\n")
f.close()

f=open('integers.txt','r')
sum=0
for l in f:
      l=l.strip()
      number=int(l)
      sum+=number
print 'The sum is',sum

Writing and reading integers from a file

f=open('myfile.txt','w')
for count in  range(5):
      f.write(str(count))
f.close()
f=open('myfile.txt','r')
t=f.read()
print t

Writing and reading string from a file

f=open('myfile.txt','w')
f.write('\n Image Processing Research Group \n www.iprg.co.in \n')
f.close()
f=open('myfile.txt','r')
text=f.read()
print text

Basic operations in Python List

l=[]
n=int(raw_input('Enter the no of elements added to list:'))
for i in range(n):
      element=int(raw_input('Enter the elements:'))
      l.append(element)
print '\nNew List is ',
m=int(raw_input('\nEnter the no of elements added to list using insert:'))
for i in range(m):
      u=int(raw_input('Enter the index to be added'))
      u1=int(raw_input('Enter the element to be added'))
      l.insert(u,u1)
print '\nNew List after insert operation is:   ',l
ch=int(raw_input('\nPress 1 to pop the last element\nPress 2 to pop the element in a particular index\nEnter the choice: '))
if ch==1:
 l.pop()
 print '\nNew List after deletion is: ',l
elif ch==2:
 p=int(raw_input('Enter the element index to be deleted'))
 l.pop(p)
 print '\nNew List after deletion is: ',l
else:
  print '\nInvalid choice'
print ' \nList elements are sorted:  ',l

To add elements in list using insert

y=[]
n=int(raw_input('Enter the no of elements added to list:'))
index=0
for i in range(n):
      element=int(raw_input('Enter the elements:'))
      y.insert(index, element)
      index=index+1
print y

To add elements inside a list using append

l=[]
n=int(raw_input('Enter the no of elements added to list:'))
for i in range(n):
      element=int(raw_input('Enter the elements:'))
      l.append(element)
print l

To count the elements in a nested list with all elements are list

a=[[3, 4, 5,8, 8 ], [5, 6, 7], [7, 8, 9]]

def count(a):
 j=0
 n=0
 for b in a:
     j=len(b)
     n=n+j
 return n

t= count(a)
print "No elements in the nested list are:",t

Count of character repetition in a string

word=str(raw_input('Enter the string:'))
n=raw_input('Enter the character to search in string:')
c=0
for i in word:
    if i==n:
      c=c+1
print 'Number of times the character repeated is',  c

To check a string is palidrome or not

k=raw_input('Enter a string:  ')

if k==k[::-1]:
    print 'String is palidrome'
else:
    print 'String is not palidrome'

Find the Armstrong Number upto a number

# Compatible in Python 2.7
k=int(raw_input('Enter the range of number:'))
for n in range(k):
 sum=0
 temp=n
 y=len(str(n))
 while(n>0):
   R=n%10
   V=R**y
   sum=sum+V
   n=n/10
 if (sum==temp):
   print 'Armstrong  Number',temp

Fibonacci sequence using functions for N numbers


# Compatible in Python 2.7

def recur_fibo(n):
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))


nterms = int(input("How many terms? "))

if nterms <= 0:
   print "Plese enter a positive integer"
else:
   print "Fibonacci sequence:"
   for i in range(nterms):
       print recur_fibo(i)

Multiplication Table

# Compatible in Python 2.7

num = int(raw_input("Display multiplication table of? "))
for i in range(1, 21):
       print num,'x',i,'=',num*i

Program to check the number is palindrome

# Compatible in Python 2.7

Number = int(raw_input("Please Enter any Number: "))
Temp=Number    # Number is stored to a temporary variable
Reverse = 0          # Initialize the reverse value to overcome garbage value storage
if Number<0:
    print 'Number is negative'
elif Number ==0:
    print 'Reverse Number is',Number
elif Number>0:
    while(Number > 0):
      Reminder = Number %10
      Reverse = (Reverse *10) + Reminder
      Number = Number /10
    print 'Reverse of a Number is',Reverse
else:
    exit()

if Temp==Reverse:
    print 'The number is palidrome'
else:
    print 'The number is not palidrome'


Python Coding Sites

Try Python                   http://campus.codeschool.com/courses/try-python/contents

Python Codecademy   https://www.codecademy.com/learn/python

Learn Python               http://www.learnpython.org/




Python Conferences on August 2016


PyCon Australia 2016
 
12 Aug. – 17 Aug. Melbourne Convention and Exhibition Centre, 1 Convention Centre Pl, South Wharf VIC 3006, Australia 


PyCon APAC 2016
 
13 Aug. – 16 Aug. Trade Center COEX Samseong 1-dong Gangnam-gu, Seoul, South Korea 


PyBay 2016
 
19 Aug. – 22 Aug. UCSF Mission Bay Conference Center, 1675 Owens St., San Francisco, CA 94143, USA 


EuroScipy 2016
 
23 Aug. – 28 Aug. Faculty of Medicine of the University of Erlangen, Germany 


PyCon MY 2016
 
26 Aug. – 29 Aug. City Campus of the International University of Malaya-Wales (IUMW), Kuala Lumpur, Malaysia

Top 10 Python Self Learning Websites

Python For Beginners

Codecademy Python

Coursera Python Course - I

Google Developers Python 

Python Course

Spoken Tutorial Foss for Python 

Learn Python

Python tutorial - TutorialsPoint

Solo Learn Python

Python EDX 

Top 10 Games uses Python Programming Language



1.                   Battlefield 2        Website
 
2.                   Crystal Space     Website    

3.                   Star Trek Bridge Commander

4.                   The Temple of Elemental Evil and Vampire: The Masquerade: Bloodlines
 
5.                   Civilization 4    Website

6.                   QuArK (Quake Army Knife)   Website
 
7.                   Cyan's Uru / Myst V    Website

8.                   Severance: Blade of Darkness 

9.                   Freedom Force   Website

10.               EVE Online (MMORPG)    Website

Values and types used in python


>>> n=1,00,000        First example we have seen of a semantic error
 >>> n
(1, 0, 0)
>>> n=12   Integer
>>> n
12
>>> n="hello"        String
>>> n
'hello'
>>> n=" Welcome to show"         Sentence
>>> n
' Welcome to show'
>>> n=3.12            Floating Number
>>> n
3.12

Welcome Everyone for the world of Python

Python is a fourth generation programming language. Guido van Rossum is the creator of Python. Here we discuss python from the basis to the expert level required for a engineer.